Java8

用流收集数据

2018-05-26  本文已影响19人  小鱼嘻嘻
List<Dish> dishes = Arrays.asList(new Dish(), new Dish(), new Dish());
        Dish max = dishes.stream().collect(
            Collectors.maxBy(
                Comparator.comparing(Dish::getName))).get();
        Dish min = dishes.stream().collect(
            Collectors.minBy(
                Comparator.comparing(Dish::getName))).get();
        Dish mmin = dishes.stream().min(Comparator.comparing(Dish::getName)).get();
        Dish mmax = dishes.stream().max(Comparator.comparing(Dish::getName)).get();
     //汇总
        Integer categaries = dishes.stream().collect(Collectors.summingInt(Dish::getCategary));
        //summarizingInt 是一个工厂  IntSummaryStatistics返回 max min count sum
        IntSummaryStatistics summaryStatistics = dishes.stream().collect(Collectors.summarizingInt(Dish::getCategary));
        summaryStatistics.getMax();
        summaryStatistics.getMin();
        summaryStatistics.getSum();
        summaryStatistics.getAverage();
        summaryStatistics.getCount();
 //字符串操作
        List<String> strings = Arrays.asList("hello", "join", "world");
        String s = strings.stream().collect(Collectors.joining());
        String collect = strings.stream().collect(Collectors.joining(","));
 //按照菜肴类型分组
   Map<String, List<Dish>> typeMaps = dishes.stream().collect(Collectors.groupingBy(Dish::getType));

groupingBy接收一个Function,这个function就是分组函数,按照我们指定的规则进行分组。这个分组函数可以是方法引用也可以是一段lambda表达式。

//多级分组 先根据类型分组,分组完成之后再按照名称分组
        Map<String, Map<String, List<Dish>>> groupMaps = dishes.stream().collect(
            Collectors.groupingBy(dish -> dish.getType(),
                Collectors.groupingBy(dish -> dish.getName())));

groupingBy(function,collector)也就是说groupingBy是可以再接收一个collector,这个collector当然可以再次进行分组。

     //分区
        Map<Boolean, List<Dish>> partionMap = dishes.stream().collect(
            Collectors.partitioningBy(dish -> dish.getType().equals("meat")));
        //分区多级函数
        Map<Boolean, Optional<Dish>> meat = dishes.stream().collect(
            Collectors.partitioningBy(dish -> dish.getType().equals("meat"),
                Collectors.maxBy(Comparator.comparing(Dish::getCategary))));

实际工作中很少用到。

收集器接口
    public interface Collector<T,A,R> {
        Supplier<A> supplier();
        BiConsumer<A,R> accumulator();
        Function<A,R> finisher();
        BinaryOperator<A> combiner();
        Set<Characteristics> characteristics();
    }

理解collector接口申明的方法

      public Supplier<List<T>> supplier() {
            return ()->new ArrayList<T>();
      } 
      public BiComsumer<List<T>,T> accumulator() {
            return (list,item)->list.add(item);
      }
    public  Function<List<T>,List<T>> finisher() {
        return Function.identity();
    }
      public BinaryOperator<List<T>> combiner() {
            return (list1,list2)->{
                    list1.addAll(list2);
                    return list1;
            }
      }
上一篇下一篇

猜你喜欢

热点阅读