zoukankan      html  css  js  c++  java
  • java8List集合根据对象的属性去重

    import static java.util.Comparator.comparingLong;
    
    import static java.util.stream.Collectors.collectingAndThen;
    
    import static java.util.stream.Collectors.toCollection;
    
    // 根据id去重
    
         List<Person> unique = persons.stream().collect(
    
                    collectingAndThen(
    
                            toCollection(() -> new TreeSet<>(comparingLong(Person::getId))), ArrayList::new)
    
            );

    分析:

    collect是一个终端操作,它接收的参数是将流中的元素累积到汇总结果的各种方式(称为收集器)

    预定义收集器包括将流元素归约和汇总到一个值.如下

    工厂方法                返回类型                  

    collectingAndThen   转换函数返回的类型   包裹另一个转换器,对其结果应用转换函数

    示例:Int count=Menu.getMenus.stream().collect(collectingAndThen(toList(),List::size))

    toCollection            Collection<T>            把流中所有元素收集到给定的供应源创建的集合中

    示例:ArrayList<Menu> menus=Menu.getMenus.stream().collect(Collectors.toCollection(ArrayList::new))

    Comparator.comparing(Function keyExtractor)生成1Comparator对象,要求keyExtractor.apply()返回值一定要实现Comparable接口。从Student对象中提取id属性,而idint类型(Integer实现了Comparable)comparingDouble()comparingLong()comparingInt()不过是comparing()更具体的版本,使用方式相同。如果是字符串比较用Comparator.comparing(Human::getName)

  • 相关阅读:
    IOS手机 html5页面 数字变成蓝色链接的原因
    html5预加载图片的写法
    jquery取消绑定的方法
    CSS3幸运大转盘最简单的写法
    深度搜索应用之黑白图像(非递归)
    springday03-go1
    springday02-go4
    spring day02-go3
    springday02-go2
    spring da-y02-go1
  • 原文地址:https://www.cnblogs.com/fswhq/p/java8_list.html
Copyright © 2011-2022 走看看