zoukankan      html  css  js  c++  java
  • java8 新特性之集合排序

    项目开发中遇到对list集合,按照某字段进行排序
    /**
    * stream.collect() 的本质由三个参数构成,
    * 1. Supplier 生产者, 返回最终结果
    * 2. BiConsumer<R, ? super T> accumulator 累加器
    * 第一个参数是要返回的集合, 第二个参数是遍历过程中的每个元素,
    * 将流中每个被遍历的元素添加到集合中
    * 3. BiConsumer<R, R> combiner 合并器, 在有并行流的时候才会有用, 一个流时代码不会走到这里
    * 将第二步遍历得到的所有流形成的list都添加到最终的list中,
    * 最后返回list1
    */

    List result = temperatureList.stream()
    .collect(
    collectingAndThen(
    toCollection(
    () -> new TreeSet<>(comparing(ExportTemperatureDto::getPersonId))
    ),
    ArrayList::new
    )
    );

    result.forEach(System.out::println);

    首先说一下collectingAndThen方法的使用-------先进行收集处理,然后将处理的集合结果,红字的两句话是理解collectingAndThen的关键,首先看一下collectingAndThen需要传递的参数:
    使用到了collectingAndThen完成根据属性进行去重的操作,对于该去重操作的关键使用到了collectingAndThen、toCollection、TreeSet,有点难以理解,当时我也是懵逼的,这里记录一下,以后肯定还会用的到。

    理解根据对象的属性进行去重的核心是,将集合放到TreeSet中,然后再将TreeSet转为List, 其中TreeSet要传入一个根据哪个属性进行比较的比较器,然后使用public ArrayList(Collection<? extends E> c)将TreeSet放入构造器中生成List。

    对于toCollection是一个通用的转为集合的操作,当然在Collectors类里面也有toList()、toSet()方法,但是都不满足于使用TreeSet来收集集合的方法,所以使用toCollection是一个通用的方法,使用TreeSet进行收集,然后传入根据哪个属性进行比较的比较器,这样就可以了。

  • 相关阅读:
    用汇编的眼光看c++(之模板函数) 四
    从B树、B+树、B*树谈到R 树 四
    how to locate dll in native c++ world / dotnet world?
    GAC和sidebyside
    ARM VS Intel
    关于dotnet下的encoding
    synchronization objects for interprocess synchronization and multithreadiing
    [remote debug]WinDBG 技巧: 如何用WinDBG远程调试程序
    [tip]transparent bmp
    Review: functor / function object
  • 原文地址:https://www.cnblogs.com/takemyjavalisfe/p/14391854.html
Copyright © 2011-2022 走看看