Java8之Predicate, Consumer,Function基础使用

代码如下:

 List<String> list = new ArrayList<>();
        list.add("c");
        list.add("a");
        list.add("b");

        //Predicate使用, 数据流条件过滤
        Predicate<String> predicate = (s)-> s.equals("a");
        Predicate<String> predicateAnd = (s)-> s.equals("b");
        Predicate<String> predicateOr = (s)-> s.equals("c");
        List<String> collect = list.stream().filter(predicate.and(predicateAnd).or(predicateOr)).collect(Collectors.toList());
        System.out.println(collect);
        System.out.println("------------------------");

        //Consumer使用, 数据流业务操作不需要返回参数
        Consumer<String> consumer = s -> {
            System.out.println(s);
        };
        list.stream().forEach(consumer);
        System.out.println("------------------------");
        list.stream().parallel().forEach(consumer);
        System.out.println("------------------------");
        list.stream().parallel().forEachOrdered(consumer);

        //Function使用, 数据流操作类型转换
        Function<String, Integer> functionCompose = (s)->{
            if(s.equals("B")){
                return 0;
            }
            return 1;
        };
        Function<Integer, Double> function = (i)->{
            if(i.equals(0)){
                return 1.0002;
            }
            return 0.0001;
        };
        //先计算functionCompose再计算function  (andThen 与 compose相反)
        Function<String, Double> compose = function.compose(functionCompose);
        List<Double> collect1 = Stream.of("A", "B", "C", "D").map(compose).collect(Collectors.toList());
        System.out.println(collect1);

 

posted @ 2021-08-09 09:18  A小小高  阅读(179)  评论(0编辑  收藏  举报