Java8中Stream的常用姿势

@Test
    public void streamTest() {

        Student stu1 = new Student(01, 19, "张三");
        Student stu2 = new Student(02, 23, "李四");
        Student stu3 = new Student(01, 28, "王五");
        Student stu4 = new Student(01, 23, "赵六");
        List<Student> list = new ArrayList<>();
        list.add(stu1);
        list.add(stu2);
        list.add(stu3);
        list.add(stu4);

        /**
         * 按操作分
         * 1、中间操作:filter(Predicate<T>), map(Function(T, R), limit, sorted(Comparator<T>), distinct,flatMap;
         * 2、终端操作:只有终端操作才能产生输出,包括:allMatch, anyMatch, noneMatch, findAny, findFirst, forEach, collect, reduce, count
         */


        /**
         * Stream<T> filter(Predicate<? super T> predicate);
         * 方法allMatch(Predicate p) 传入一个断言型函数,
         * 对流中所有的元素进行判断,找出年龄大于23的学生,
         */
        List<Student> filterList = list.stream().filter(stu -> stu.getAge() > 23).collect(Collectors.toList());
        System.out.println(filterList);


        /**
         * Stream<T> distinct();
         * distinct,去重
         *
         */
        List<Student> distinctList = list.stream().distinct().collect(Collectors.toList());
        System.out.println(distinctList);


        /**
         * Stream<T> limit(long maxSize);
         * limit,输出前n个
         *
         */
        List<Student> limitList = list.stream().limit(2).collect(Collectors.toList());
        System.out.println(limitList);

        /**
         * Stream<T> skip(long n);
         * skip,跳过前几个
         */
        List<Student> skipList = list.stream().skip(2).collect(Collectors.toList());
        System.out.println(skipList);


        /**
         * long count();
         * 返回总数
         *
         */
        long count = list.stream().filter(stu -> stu.getAge() > 19).count();
        System.out.println(count);


        /**
         *
         * <R> Stream<R> map(Function<? super T, ? extends R> mapper);
         * map 操作是将流中的元素进行再次加工形成一个新流。
         * map, 映射,T -> R
         */
        List<Integer> toMapList = list.stream().map(Student::getAge).collect(Collectors.toList());
        System.out.println(toMapList);

        /**
         * <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
         * flatMap,将每个元素产生的中间集合合并成一个大集合;接收的Function将T->Stream<R>
         *
         */
//         flatMap 提取 List<Students>  map 提取年龄
//        List<Integer> ages = grades.stream()
//        .flatMap(grade -> grade.getStudents().stream())
//        .map(Student::getAge).collect(Collectors.toList());//例1

        Arrays.asList(new String[]{"hello", "world"}).stream().map(p -> p.split(""))
                .flatMap(Arrays::stream)  //.flatMap(p -> Arrays.stream(p))
                .distinct().forEach(System.out::print);//例2
        // 输出:helowrd




        //匹配
        /**
         * boolean anyMatch(Predicate<? super T> predicate);
         * 方法allMatch(Predicate p) 传入一个断言型函数,
         * 对流中所有的元素进行判断,如果都满足返回true,
         * 否则返回false。
         *
         */
        //判断学生年龄是否都大于18
        boolean flag1 = list.stream().allMatch(stu -> stu.getAge() > 18);
        System.out.println(flag1);
        //运行结果 true

        /**
         * boolean anyMatch(Predicate<? super T> predicate);
         * 方法allMatch(Predicate p) 传入一个断言型函数,
         * 对流中所有的元素进行判断,有一个满足就返回true,
         * 否则返回false。
         */
        boolean flag2 = list.stream().anyMatch(stu -> stu.getAge() > 18);
        System.out.println(flag2);

        /**
         * boolean anyMatch(Predicate<? super T> predicate);
         * 方法allMatch(Predicate p) 传入一个断言型函数,
         * 对流中所有的元素进行判断,都不满足返回true,
         * 否则返回false。
         */
        boolean flag3 = list.stream().noneMatch(stu -> stu.getAge() > 18);
        System.out.println(flag3);


        //查找 与其他操作结合使用
        /**
         *Optional<T> findAny();
         * 查找,与其它操作结合使用
         * 多个对象符合,返回第一个
         *
         */
        Optional<Student> any = list.stream().filter(stu -> stu.getAge() > 19).findAny();
        System.out.println(any.get());


        /**
         * Optional<T> findFirst();
         * 查找,与其它操作结合使用
         * 多个对象符合,返回第一个
         */
        Optional<Student> first = list.stream().filter(stu -> stu.getAge() > 19).findFirst();
        System.out.println(first.get());



        //reduct 归约
        /**
         *
         * Optional<T> reduce(BinaryOperator<T> accumulator);
         * 对Stream中的数据通过累加器accumulator迭代计算,最终得到一个Optional对象
         * 需要一个函数式接口参数,该函数式接口需要两个参数,返回一个结果(reduce中返回的结果会作为下次累加器计算的第一个参数),
         * 也就是所讲的累加器。所以reduce(BinaryOperator<T> accumulator)方法可以如下调用:
         */
        List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5, 6);
        Optional<Integer> reduce1 = list1.stream().reduce((acc, item) -> acc += item);
        System.out.println(reduce1.get());
        //运行结果 21

        /***
         *  T reduce(T identity, BinaryOperator<T> accumulator);
         * 提供一个跟Stream中数据同类型的初始值identity,通过累加器accumulator迭代计算Stream中的数据,
         * 得到一个跟Stream中数据相同类型的最终结果,可以如下调用:
         */
        Integer reduce2 = list1.stream().reduce(100, (acc, item) -> acc += item);
        System.out.println(reduce2);
        //运行结果 121

        /**
         * <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);
         * BiFunction的三个泛型类型分别是U、 ? super T、U,参考BiFunction函数式接口apply方法定义可以知道,
         * 累加器累加器通过类型为U和? super T的两个输入值计算得到一个U类型的结果返回。也就是说这种reduce方法,
         * 提供一个不同于Stream中数据类型的初始值,通过累加器规则迭代计算Stream中的数据,最终得到一个同初始值同类型的结果
         */
        ArrayList<Integer> reduce = list1.stream().reduce(Lists.newArrayList(10), (acc, item) -> {
            acc.add(item);
            return acc;
        }, (acc, item) -> {
            acc.addAll(item);
            return acc;
        });
        System.out.println(reduce);
        //运行结果 [1, 1, 2, 3, 4, 5, 6]
        //通过运行结果可以看出,第三个参数定义的规则并没有执行。这是因为reduce的第三个参数是在使用parallelStream的reduce操作时,合并各个流结果的,本例中使用的是stream,所以第三个参数是不起作用的


        /**
         * IntStream mapToInt(ToIntFunction<? super T> mapper);
         * 数值流->统计方法 相加
         */

        int sum = list.stream().mapToInt(Student::getId).sum();
        System.out.println(sum);


        //收集器
        /**
         * groupingBy 分组
         */
        Map<Integer, List<Student>> groupByList = list.stream().collect(groupingBy(Student::getAge));
        System.out.println(groupByList);

        /**
         * groupingBy 分组
         */
        Map<Integer, Map<Integer, List<Student>>> doubleGroupByList = list.stream().collect(groupingBy(Student::getId, groupingBy(Student::getAge)));
        System.out.println(doubleGroupByList);

        /**
         * groupingBy 分组
         *
         */
        Map<Integer, Student> groupByList2 = list.stream().collect(groupingBy(Student::getId, collectingAndThen(maxBy(comparing(Student::getAge)), Optional::get)));
        System.out.println(groupByList2);
        

    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值