java8 stream常用用法(转载)

https://blog.csdn.net/y_k_y/article/details/84633001

 

重点提一下anyMatch

       allMatch:接收一个 Predicate 函数,当流中每个元素都符合该断言时才返回true,否则返回false
        noneMatch:接收一个 Predicate 函数,当流中每个元素都不符合该断言时才返回true,否则返回false
        anyMatch:接收一个 Predicate 函数,只要流中有一个元素满足该断言则返回true,否则返回false
        findFirst:返回流中第一个元素
        findAny:返回流中的任意元素
        count:返回流中元素的总个数
        max:返回流中元素最大值
        min:返回流中元素最小值

用法例子1

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
 
boolean allMatch = list.stream().allMatch(e -> e > 10); //false
boolean noneMatch = list.stream().noneMatch(e -> e > 10); //true
// 下方代码的含义是,对list里的每一个数据,看看满不满足大于4,只要有一个满足,就算true
boolean anyMatch = list.stream().anyMatch(e -> e > 4); //true Integer findFirst = list.stream().findFirst().get(); //1 Integer findAny = list.stream().findAny().get(); //1 long count = list.stream().count(); //5 Integer max = list.stream().max(Integer::compareTo).get(); //5 Integer min = list.stream().min(Integer::compareTo).get(); //1

用法例子2

List<Integer> result = Lists.newArrayList(1,2,3);
List<Integer> ids = Lists.newArrayList(1,2);

//  对result里面的每一个函数,调用ids.contains,看看ids里面有无result里的数,有的话,算true
boolean a = result.stream().anyMatch(ids::contains);

 

posted @ 2021-01-22 20:37  弓呆的胖次  阅读(449)  评论(0编辑  收藏  举报