STREAM APIを使ってみた
anyMatch:判定(一部合致)
セット
List<TestBean> list = new ArrayList<>();
TestBean bean1 = new TestBean();
bean1.setCd("A");
bean1.setName("商品A");
bean1.setNum(100);
list.add(bean1);
TestBean bean2 = new TestBean();
bean2.setCd("B");
bean2.setName("商品B");
bean2.setNum(100);
list.add(bean2);
実行
list.stream().anyMatch(b->b.getCd().equals("A"));//true
list.stream().anyMatch(b->b.getCd().equals("C"));//false
allMatch: 判定(全て合致)
セット
List<TestBean> list = new ArrayList<>();
TestBean bean1 = new TestBean();
bean1.setCd("A");
bean1.setName("商品A");
bean1.setNum(100);
list.add(bean1);
TestBean bean2 = new TestBean();
bean2.setCd("A");
bean2.setName("商品A");
bean2.setNum(100);
list.add(bean2);
実行
list.stream().allMatch(b->b.getCd().equals("A"));//true
list.stream().allMatch(b->b.getCd().equals("B"));//false
noneMatch:判定(全て非合致)
セット
List<TestBean> list = new ArrayList<>();
TestBean bean1 = new TestBean();
bean1.setCd("A");
bean1.setName("商品A");
bean1.setNum(100);
list.add(bean1);
TestBean bean2 = new TestBean();
bean2.setCd("A");
bean2.setName("商品A");
bean2.setNum(100);
list.add(bean2);
実行
list.stream().noneMatch(b->b.getCd().equals("A"));//false
list.stream().noneMatch(b->b.getCd().equals("B"));//true
max:最大値を返す
セット
List<TestBean> list = new ArrayList<>();
TestBean bean1 = new TestBean();
bean1.setCd("A");
bean1.setName("商品A");
bean1.setNum(100);
list.add(bean1);
TestBean bean2 = new TestBean();
bean2.setCd("C");
bean2.setName("商品C");
bean2.setNum(200);
list.add(bean2);
実行
list.stream().map(b->b.getNum()).max(Comparator.naturalOrder()).get();//200
findAny:任意の値を返す
セット
List<TestBean> list = new ArrayList<>();
TestBean bean1 = new TestBean();
bean1.setCd("A");
bean1.setName("商品A");
bean1.setNum(100);
list.add(bean1);
TestBean bean2 = new TestBean();
bean2.setCd("C");
bean2.setName("商品C");
bean2.setNum(200);
list.add(bean2);
実行
list.stream().findAny().map(b->b.getCd()).orElse(null);//A
findFirst:先頭の値を返す
セット
List<TestBean> list = new ArrayList<>();
TestBean bean1 = new TestBean();
bean1.setCd("A");
bean1.setName("商品A");
bean1.setNum(100);
list.add(bean1);
TestBean bean2 = new TestBean();
bean2.setCd("C");
bean2.setName("商品C");
bean2.setNum(200);
list.add(bean2);
実行
list.stream().findFirst().map(b->b.getCd()).orElse(null);//A
sum:合計を返す
セット
List<TestBean> list = new ArrayList<>();
TestBean bean1 = new TestBean();
bean1.setCd("A");
bean1.setName("商品A");
bean1.setNum(100);
list.add(bean1);
TestBean bean2 = new TestBean();
bean2.setCd("B");
bean2.setName("商品B");
bean2.setNum(100);
list.add(bean2);
TestBean bean3 = new TestBean();
bean3.setCd("A");
bean3.setName("商品A");
bean3.setNum(100);
list.add(bean3);
実行
list.stream().filter(b->b.getCd().equals("A")).mapToInt(b->b.getNum()).sum();//200