☆☆☆★☆☆☆

唯有努力才能活成自己想要活成的样子

导航

Java 流收集器 ( Stream Collectors )

Java 流收集器异常强大,通常可以有以下等方面的操作:

Collectors.groupingBy() 分组;Collectors.counting() 计数;分组排序再计算;并行分组处理

平常使用代码案例

 一、分组操作 :

  原型:Collector<T,?,Map<K,List<T>>> groupingBy(Function<? super T,? extends K> classifier)

  实例:

  (1)按照某个字段分组

    Map<Integer, List<CanOrgBean>> groupCanOrgBean = canList.stream().collect(Collectors.groupingBy(canOrgBean -> canOrgBean.getCanType()));

  (2)list<Integer>按照值分组

    Map<Integer, List<Integer>> collect = listLevelVal.stream().collect(Collectors.groupingBy(Integer::intValue));

  (3)取出list中对象的某一属性

    List<String> stIdList1 = stuList.stream().map(Student::getId).collect(Collectors.toList());

    (4)过滤List中Object的Name字段为空的情况

    List<Object> list = list.stream().filter(item -> item.getName() != null).collect(Collectors.toList());

    (5)根据List列表对象某个字段进行去重操作

    List<Integer> maxList2 = list.stream().map(Object::getMax).distinct().collect(Collectors.toList());

 

 二、计数:

  原型:Collector<T,?,M> groupingBy(Function<? super T,? extends K> classifier, Supplier<M> mapFactory, Collector<? super T,A,D> downstream)

  实例:

  (1)分组计数:

    Map<Integer, Long> groupCanOrgBeanCount = canList.stream().collect(Collectors.groupingBy(CanOrgBean::getCanType, Collectors.counting()));

  (2)分组排序再计算:

    TreeMap<Integer, Double> collect = canList.stream().collect(Collectors.groupingBy(CanOrgBean::getCanType, TreeMap::new, Collectors.averagingDouble(CanOrgBean::getCanValue)));

    (3) 计算一个List对象中某个字段总和

    int total = list.stream().mapToInt(User::getAge).sum();

三、排序 :
  实例:
  (1)集合对象中的一个字段对其进行排序
    Collections.sort(list, (o1, o2) -> o1.getCustomerCount() - o2.getCustomerCount());

 

四、数组类型转速

  实例:

  (1)【String数组】转成【Byte数组】:

    Byte[] bytes1 = (Byte[]) ConvertUtils.convert(arr, Byte.class);//java提供的common中可以使用

    Byte[] bytes2 = Arrays.stream(arr).map(Byte::valueOf).collect(Collectors.toList()).stream().toArray(Byte[]::new);

  (2)【String数组】转成【Int数组】:

    int[] ints1 = Arrays.stream(arr).mapToInt(Integer::valueOf).toArray();

    int[] ints2 = Arrays.stream(arr).mapToInt(i -> Integer.valueOf(i)).toArray();

    

 

后续.......





posted on 2020-06-28 16:19  Yr-Zhang  阅读(659)  评论(0编辑  收藏  举报