zoukankan      html  css  js  c++  java
  • java8 stream

    java8的stream用户

      数据准备:

    public class Dish {
        public String name;    //菜的名称
        public Boolean vegetaian;  //是否为素
        public Integer calories;   //卡路里
        public Type type;      //类型(肉 鱼 其他)
        public Dish() {
        }
        public Dish(String name, Boolean vegetaian, Integer calories, Type type) {
            this.name = name;
            this.vegetaian = vegetaian;
            this.calories = calories;
            this.type = type;
        }
        public enum Type {MEAT, FISH, OTHER} //肉 鱼 其他
    }
    public class DishList {
    
        public static List<Dish> getDishList() {
            List<Dish> dishList = Arrays.asList(
                    new Dish("pork", false, 800, Dish.Type.MEAT),
                    new Dish("beef", false, 700, Dish.Type.MEAT),
                    new Dish("chicken", false, 400, Dish.Type.MEAT),
                    new Dish("french fries", true, 530, Dish.Type.OTHER),
                    new Dish("rice", true, 350, Dish.Type.OTHER),
                    new Dish("season fruit", true, 120, Dish.Type.OTHER),
                    new Dish("pizza", true, 550, Dish.Type.OTHER),
                    new Dish("prawns", false, 300, Dish.Type.FISH),
                    new Dish("salmon", false, 450, Dish.Type.FISH)
            );
            return dishList;
        }
    }

      1:filter

        /**
         * filter 过滤结果为true的
         * 过滤“calories:卡路里”小于500的
         */
        @Test
        public void filter() {
            List<Dish> dishList = DishList.getDishList();
            List<Dish> collect = dishList.stream().filter(dish -> dish.getCalories() < 500).collect(Collectors.toList());
            collect.forEach(System.out::println);
        }

      2:distinct

        /**
         * 去重:过滤元素相同的
         */
        @Test
        public void distinct() {
            List<Integer> list = Arrays.asList(1, 2, 3, 4, 1, 2);
            list.stream().distinct().forEach(System.out::println);
        }

      3:   skip

      /**
         * skip 跳过前n个
         */
        @Test
        public void skip() {
            List<Dish> dishList = DishList.getDishList();
            dishList.stream().skip(5).forEach(System.out::println);
        }

      4:    limit

        /**
         * limit 只保留前n个
         */
        @Test
        public void limit() {
            List<Dish> dishList = DishList.getDishList();
            dishList.stream().limit(5).forEach(System.out::println);
        }

      5: map

       /**
         * map 映射
         */
        @Test
        public void map() {
            List<Dish> dishList = DishList.getDishList();
            Function<Dish, String> function1 = dish -> dish.getName() + ",";    //转换的结果可以为任意类型与形式
            Function<Dish, String> function2 = Dish::getName;
            List<String> collect = dishList.stream().map(function1).collect(Collectors.toList());
            collect.forEach(System.out::println);
        }

      6: flatMap

    /**
         * flatMap:扁平化
         * 获取每一个元素,并去重

        对hello,world分割去重
    */
    @Test
    public void filter3() {
    String[] words = {"hello", "world"};
    // 将words换成流,stream中有 "hello","world" 两个元素
    Stream<String> stream = Arrays.stream(words);
    // 将stream中每个元素映射成“字符串数组” ,stream1中有“h,e,l,l,o”,"w,o,r,l,d"
    Stream<String[]> stream1 = stream.map(item -> item.split(""));
    // 将流中的每个值都换成另一个流,然后把所有的流链接成1个流(将stream1映射成“h,e,l,l,o,w,o,r,l,d”)
    Stream<String> stream2 = stream1.flatMap(Arrays::stream);
    stream2.distinct().forEach(System.out::println);
    }
    
    

     Match

      7:allMatch

       /**
         * 全匹配
         * 所有的dish的calories都<400吗?
         */
        @Test
        public void allMatch() {
            List<Dish> dishList = DishList.getDishList();
            boolean b = dishList.stream().allMatch(item -> item.getCalories() < 400);
            System.out.println(b);
        }

      8:anyMatch

    /**
     * 存在一个匹配
     * 至少1个dish的calories都<400吗?
     */
    @Test
    public void anyMatch() {
        List<Dish> dishList = DishList.getDishList();
        boolean b = dishList.stream().anyMatch(item -> item.getCalories() < 400);
        System.out.println(b);
    }

      9:noneMatch

    /**
     * 不存在匹配
     * 所有的dish的calories都不<400吗?
     */
    @Test
    public void noneMatch() {
        List<Dish> dishList = DishList.getDishList();
        boolean b = dishList.stream().noneMatch(item -> item.getCalories() < 400);
        System.out.println(b);
    }

     Find

      10:findAny

        @Test
        public void findAny() {
            List<Dish> dishList = DishList.getDishList();
            Dish dish = dishList.stream().findAny().orElse(new Dish());
            System.out.println(dish);
        }

      11:findFirst

       @Test
        public void findFirst() {
            List<Dish> dishList = DishList.getDishList();
            Dish dish = dishList.stream().findFirst().orElse(new Dish());
            System.out.println(dish);
        }

    Reduce 规约(将流中的元素组合,规约成一个值)

      12:reduce

    @Test
    public void reduce1() {
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
    IntBinaryOperator operator = (s1, s2) -> s1 + s2;
    OptionalInt reduce = list.stream().mapToInt(Integer::intValue).reduce(operator);
    int asInt = reduce.getAsInt();
    System.out.println(asInt);

    //IntBinaryOperator 的 int applyAsInt(int left, int right); 方法,接受两个参数
    //mapToInt(Integer::intValue) 将int值拆箱
    //getAsInt 从Optional取出值(如果值不存在则抛出异常) 使用 int asInt = reduce.orElse(0); 获取值,或者使用isPresient判断再取值
    }
    
    
    
    

      13:reduce

        @Test
        public void reduce2() {
            List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
            IntBinaryOperator operator = (s1, s2) -> s1 + s2;
            int reduce = list.stream().mapToInt(Integer::intValue).reduce(0,operator); //使用默认值
        //int reduce = list.stream().mapToInt(Integer::intValue).reduce(0,Integer::sum)  //Integer::sum 求和  Integet::max 最大值  Integer::min 最小值
            System.out.println(reduce);
        }

      14:boxed

        /**
         * 包装与拆箱
         */
        @Test
        public void boxed() {
            List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
            IntStream intStream = list.stream().mapToInt(Integer::intValue);    //拆箱
            Stream<Integer> boxed = intStream.boxed();  //包装
            List<Integer> collect = boxed.collect(Collectors.toList());
        }

    Optional   (待完善)

      15:Optional 

        /**
         * Optional 包装
         */
        @Test
        public void optional() {
            //包含元素为null的Optional
            Optional empty = Optional.empty();
            boolean present = empty.isPresent();  // false
    
            //包含元素必须不为null
            Optional<String> of = Optional.of("optional");
            //包含元素为null调用 empty()方法,不为null调用 of()方法
            Optional<String> optional = Optional.ofNullable("optional");
        }

    Collectors

      16:toList

        /**
         * toList 
       * 筛选“vegetaian”,-> list
    */ @Test public void toList() { List<Dish> dishList = DishList.getDishList(); List<Dish> collect = dishList.stream().filter(Dish::getVegetaian).collect(Collectors.toList()); }

      17:toSet

       /**
         * toSet
       *将dish -> name->set
    */ @Test public void toSet() { List<Dish> dishList = DishList.getDishList(); Set<String> collect = dishList.stream().map(Dish::getName).collect(Collectors.toSet()); }

      18:toMap

        /**
         * toMap
       * key:name value:dish
    */ @Test public void toMap() { List<Dish> dishList = DishList.getDishList(); Map<String, Dish> collect = dishList.stream().collect(Collectors.toMap(Dish::getName, Function.identity())); }

      19:toConcurrentMap

       /**
         * toConcurrentMap
         * key:name value:自身 ->存放到ConcurrentMap中
         */
        @Test
        public void toConcurrentMap() {
            List<Dish> dishList = DishList.getDishList();
            ConcurrentMap<String, Dish> collect = dishList.stream().collect(Collectors.toConcurrentMap(Dish::getName, Function.identity()));
        }

      20:averaging

        /**
         * 平均值
       * 返回的都是double类型,区别在“参数”限制
    */ @Test public void averaging() { List<Dish> dishList = DishList.getDishList(); Double aInt = dishList.stream().collect(Collectors.averagingInt(Dish::getCalories)); Double aDouble = dishList.stream().collect(Collectors.averagingDouble(Dish::getCalories)); Double aLong = dishList.stream().collect(Collectors.averagingLong(Dish::getCalories)); }

      21:collectingAndThen

        /**
         * 附加动作
         * collectingAndThen(Collector<T,A,R> downstream,Function<R,RR> finisher)
         * Collector 执行的结果作为 Function 的入参
         * 备注:Collectors调用的方法返回的即是Collector类型
         */
        @Test
        public void collectingAndThen() {
            List<Dish> dishList = DishList.getDishList();
            String collect = dishList.stream().collect(Collectors.collectingAndThen(Collectors.averagingInt(Dish::getCalories), item -> "结果为:" + item));
            System.out.println(collect);
        }

      22:unmodifiableList

        /**
         * 只读
         *
         */
        @Test
        public void unmodifiableList() {
            List<Dish> dishList = DishList.getDishList();
            List<Dish> collect = dishList.stream().collect(Collectors.collectingAndThen(Collectors.toList(),Collections::unmodifiableList));
    
        }

      23:counting

       @Test
        public void counting(){
            List<Dish> dishList = DishList.getDishList();
            Long collect = dishList.stream().filter(item->item.getCalories()<0).collect(Collectors.counting());
            System.out.println(collect);
        }

      24:groupingBy

    @Test
    public void groupingBy(){
    List<Dish> dishList = DishList.getDishList();
    Map<Dish.Type, List<Dish>> collect = dishList.stream().collect(Collectors.groupingBy(Dish::getType));
    System.out.println(collect);
    }

      25:groupingBy

    /**
    * 先根据type分类,再统计每个分类的个数
    * groupingBy(Function<? super T, ? extends K> classifier,Collector<? super T, A, D> downstream)
    */
    @Test
    public void groupingBy(){
    List<Dish> dishList = DishList.getDishList();
    Map<Dish.Type, Long> collect = dishList.stream().collect(Collectors.groupingBy(Dish::getType, Collectors.counting()));
    System.out.println(collect);
    }

      26:groupingBy

        /**
         * 先根据type分类,再统计每个分类的个数
         *  groupingBy(Function<? super T, ? extends K> classifier, Supplier<M> mapFactory, Collector<? super T, A, D> downstream)
         */
        @Test
        public void groupingBy(){
            List<Dish> dishList = DishList.getDishList();
            TreeMap<Dish.Type, Long> collect = dishList.stream().collect(Collectors.groupingBy(Dish::getType, TreeMap::new, Collectors.counting()));
            System.out.println(collect);
        }

      27:summarizingInt

       /**
         * 统计 总数,最小值,均值,最大值
         * IntSummaryStatistics{count=9, sum=4200, min=120, average=466.666667, max=800}
         */
        @Test
        public void summarizingInt() {
            List<Dish> dishList = DishList.getDishList();
            IntSummaryStatistics collect = dishList.stream().collect(Collectors.summarizingInt(Dish::getCalories));
            System.out.println(collect);  //     * IntSummaryStatistics{count=9, sum=4200, min=120, average=466.666667, max=800}
        }

      28:groupingByConcurrent

      /**
         * 分组,返回CocurrentMap类型
         */
        @Test
        public void groupingByConcurrent() {
            List<Dish> dishList = DishList.getDishList();
            ConcurrentMap<Dish.Type, List<Dish>> collect = dishList.stream().collect(Collectors.groupingByConcurrent(Dish::getType));
            System.out.println(collect);
        }

      29:groupingByConcurrent

    /**
         * 分组并统计,返回CocurrentMap类型
         */
        @Test
        public void groupingByConcurrent() {
            List<Dish> dishList = DishList.getDishList();
            ConcurrentMap<Dish.Type, Long> collect = dishList.stream().collect(Collectors.groupingByConcurrent(Dish::getType, Collectors.counting()));
            System.out.println(collect);
        }

      30:groupingByConcurrent

        /**
         * 分组并统计,返回ConcurrentSkipListMap类型(调表类型)
         */
        @Test
        public void groupingByConcurrent() {
            List<Dish> dishList = DishList.getDishList();
            ConcurrentSkipListMap<Dish.Type, Long> collect = dishList.stream().collect(Collectors.groupingByConcurrent(Dish::getType, ConcurrentSkipListMap::new, Collectors.counting()));
            System.out.println(collect);
        }

      31:joining

        /**
         * joining,拼接,参数必须为 CharSequence
         */
        @Test
        public void joining() {
            List<Dish> dishList = DishList.getDishList();
            String collect = dishList.stream().map(Dish::getName).collect(Collectors.joining());
            System.out.println(collect);
        }

      32:joining

     /**
         * joining,拼接,分割
         */
        @Test
        public void joining() {
            List<Dish> dishList = DishList.getDishList();
            String collect = dishList.stream().map(Dish::getName).collect(Collectors.joining(","));
            System.out.println(collect);
        }

      33:joining

        /**
         * joining,拼接,分割,加前后缀
         */
        @Test
        public void joining() {
            List<Dish> dishList = DishList.getDishList();
            String collect = dishList.stream().map(Dish::getName).collect(Collectors.joining(",","name[","]"));
            System.out.println(collect);
        }

      34:mapping

        /**
         * mapping,先映射,再将结果拼接
         */
        @Test
        public void mapping() {
            List<Dish> dishList = DishList.getDishList();
            String collect = dishList.stream().collect(Collectors.mapping(Dish::getName, Collectors.joining(",", "name[", "]")));
            System.out.println(collect);
        }

      35:maxBy

     /**
         * maxBy:最大值
         * maxBy(Comparator<? super T> comparator)
         * Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor)
         */
        @Test
        public void maxBy() {
            List<Dish> dishList = DishList.getDishList();
            Dish dish = dishList.stream().collect(Collectors.maxBy(Comparator.comparingInt(Dish::getCalories))).orElseGet(null);
            System.out.println(dish);
        }

      36:minBy

     /**
         * minBy:最小值
         * minBy(Comparator<? super T> comparator)
         * Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor)
         */
        @Test
        public void minBy() {
            List<Dish> dishList = DishList.getDishList();
            Dish dish = dishList.stream().collect(Collectors.minBy(Comparator.comparingInt(Dish::getCalories))).orElseGet(null);
            System.out.println(dish);
        }

      37:partitioningBy

        /**
         * partitioningBy:分类  (根据是否是vegetaian分类)
         */
        @Test
        public void partitioningBy() {
            List<Dish> dishList = DishList.getDishList();
            Map<Boolean, List<Dish>> collect = dishList.stream().collect(Collectors.partitioningBy(Dish::getVegetaian));
            System.out.println(collect);
        }

       38:partitioningBy

       /**
         * partitioningBy:分类  (根据是否是vegetaian分类,然后分别统计卡路里均值)
         */
        @Test
        public void partitioningBy() {
            List<Dish> dishList = DishList.getDishList();
            Map<Boolean, Double> collect = dishList.stream().collect(Collectors.partitioningBy(Dish::getVegetaian, Collectors.averagingInt(Dish::getCalories)));
            System.out.println(collect);
        }

      39:reducing 

      /**
         * reducing 规约 :找出卡路里最大的一个
         * Collector<T, ?, Optional<T>>  reducing(BinaryOperator<T> op)
         * BinaryOperator<T> maxBy(Comparator<? super T> comparator)
         * Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor)
         */
        @Test
        public void reducing() {
            List<Dish> dishList = DishList.getDishList();
            Optional<Dish> collect = dishList.stream().collect(Collectors.reducing(BinaryOperator.maxBy(Comparator.comparingInt(Dish::getCalories))));
            System.out.println(collect.orElse(null));
        }

      40:reducing 

     /**
         * reducing 规约 :找出卡路里最大的一个 (默认值为0)
    
         */
        @Test
        public void reducing() {
            List<Dish> dishList = DishList.getDishList();
            Integer collect = dishList.stream().map(Dish::getCalories).collect(Collectors.reducing(0, (d1, d2) -> d1 - d2));
            System.out.println(collect);
        }

      41:reducing 

        /**
         * reducing 规约 :找出卡路里最大的一个 (默认值为0)
    
         */
        @Test
        public void reducing() {
            List<Dish> dishList = DishList.getDishList();
            Integer collect = dishList.stream().collect(Collectors.reducing(0,Dish::getCalories, (d1, d2) -> d1 - d2));
            System.out.println(collect);

      42:summarizingDouble

        /**
         * summarizingDouble
        参考27
    */ @Test public void summarizingDouble() { List<Dish> dishList = DishList.getDishList(); DoubleSummaryStatistics collect = dishList.stream().collect(Collectors.summarizingDouble(Dish::getCalories)); System.out.println(collect); }

      43:summarizingLong

      /**
         * summarizingLong
         参考27
    */ @Test public void summarizingLong() { List<Dish> dishList = DishList.getDishList(); LongSummaryStatistics collect = dishList.stream().collect(Collectors.summarizingLong(Dish::getCalories)); System.out.println(collect); }

      44:summingInt  

       /**
         * summingInt  根据calories总计
         */
        @Test
        public void summingInt() {
            List<Dish> dishList = DishList.getDishList();
            Integer collect = dishList.stream().collect(Collectors.summingInt(Dish::getCalories));
            System.out.println(collect);
        }

      45:toCollection

       /**
         * toCollection
         * toCollection(Supplier<C> collectionFactory)
         */
        @Test
        public void toCollection() {
            List<Dish> dishList = DishList.getDishList();
            LinkedHashSet<Dish> collect = dishList.stream().collect(Collectors.toCollection(LinkedHashSet::new));
            System.out.println(collect);
        }

      46:toMap

        /**
         * toMap
         * toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper)
         */
        @Test
        public void toMap() {
            List<Dish> dishList = DishList.getDishList();
            Map<String, Integer> collect = dishList.stream().collect(Collectors.toMap(Dish::getName, Dish::getCalories));
            System.out.println(collect);
        }

      47:toMap

     /**
         * toMap:keyMapper:根据type分类;valueMapper:获取每个dish的calories; mergeFunction对同类型的calories相加; mapSupplier:返回值类型
         * toMap(Function<? super T, ? extends K> keyMapper,Function<? super T, ? extends U> valueMapper,  BinaryOperator<U> mergeFunction,Supplier<M> mapSupplier)
         * mergeFunction为对valueMapper的结果计算
         */
        @Test
        public void toMap() {
            List<Dish> dishList = DishList.getDishList();
            ConcurrentHashMap<Dish.Type, Integer> collect = dishList.stream().collect(Collectors.toMap(Dish::getType, Dish::getCalories, (a1, a2) -> a1 + a2, ConcurrentHashMap::new));
            System.out.println(collect);    //{OTHER=1550, MEAT=1900, FISH=750}
        }

      48:toConcurrentMap

       /**
         * toConcurrentMap:keyMapper:根据type分类;valueMapper:获取每个dish的calories; mergeFunction对同类型的calories相加; mapSupplier:返回值类型
         * toConcurrentMap(Function<? super T, ? extends K> keyMapper,Function<? super T, ? extends U> valueMapper,  BinaryOperator<U> mergeFunction,Supplier<M> mapSupplier)
         * mergeFunction为对valueMapper的结果计算
         */
        @Test
        public void toConcurrentMap() {
            List<Dish> dishList = DishList.getDishList();
            ConcurrentHashMap<Dish.Type, Integer> collect = dishList.stream().collect(Collectors.toConcurrentMap(Dish::getType, Dish::getCalories, (a1, a2) -> a1 + a2, ConcurrentHashMap::new));
            System.out.println(collect);    //{OTHER=1550, MEAT=1900, FISH=750}
        }
  • 相关阅读:
    CentOS 6.5 安装 VNC Server
    vs2008出错
    MySQL 尽量避免使用 TIMESTAMP
    excel中生成32位随机id
    库存扣减和锁
    精通 MySQL 索引
    Java代码性能优化
    RocketMQ 消息丢失场景分析及如何解决
    Java 8 的内存结构
    Spring Boot + MyBatis + MySQL 实现读写分离
  • 原文地址:https://www.cnblogs.com/draymond/p/11853283.html
Copyright © 2011-2022 走看看