• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

JAVA8 Stream查找、匹配、归约

java8 来源:狮子头儿 1次浏览
List<Student> students = Arrays.asList(
            new Student(1,"zhangsan","class1",18,60),
            new Student(2,"lisi","class1",20,59),
            new Student(3,"wangwu","class2",18,100),
            new Student(4,"wangwu","class2",16,100),
            new Student(5,"wangwu","class2",22,100),
            new Student(6,"zhaoliu","class2",18,80));
/**
 * 查找、匹配
 *  allMatch(Predicate p) 检查是否匹配所有元素
 * anyMatch(Predicate p) 检查是否至少匹配一个元素
 * noneMatch(Predicate p) 检查是否没有匹配所有元素
 * findFirst() 返回第一个元素
 * findAny() 返回当前流中的任意元素
 * count() 返回流中元素总数
 * max(Comparator c) 返回流中最大值
 * min(Comparator c) 返回流中最小值
*/
@Test
    public void test5(){
        System.out.println("allMatch:"+students.stream().allMatch(e->e.getClazz().contains("class1")));
        System.out.println("anyMatch:"+students.stream().anyMatch(e->e.getGrade()==100));
        System.out.println("noneMatch:"+students.stream().noneMatch(e->e.getGrade()==100));
        System.out.println("findFirst:"+students.stream().findFirst());
        System.out.println("findAny:"+students.stream().findAny());
        System.out.println("count:"+students.stream().filter(e->e.getGrade()==100).count());
        System.out.println("max:"+students.stream().map(e->e.getAge()).max(Double::compare).get());
        System.out.println("min:"+students.stream().map(Student::getAge).min(Double::compare));
    }

输出结果为:

/**
 * 归约
 * reduce(T iden, BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回 T
 * reduce(BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回 Optional<T>
 */
    @Test
    public void test6(){
        Integer sum = students.stream().map(e->e.getGrade()).reduce(0,(e1, e2)->e1+e2);
        Optional<Integer> suma = students.stream().map(Student::getGrade).reduce(Integer::sum);
        System.out.println(sum+"-----"+suma);//499-----Optional[499]
        Integer[] nums = new Integer[]{1,3,5,7,9};
        Arrays.asList(nums).stream()
                .map(e->e*e).forEach(System.out::println);// 1 9 25 49 81
        Optional<Integer> result = Arrays.asList(nums).stream()
                .reduce(Integer::sum); 
        System.out.println(result.get());//25
    }

 


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)