Stream的去重排序

List排序

List<Integer> list = new ArrayList<>();
list.add(50);
list.add(25);
list.add(25);
list.add(98);
list.add(32);
List<Integer> collect = list.stream().distinct().sorted().collect(Collectors.toList());
System.out.println("去重正序" + collect);
List<Integer> collect1 = list.stream().distinct().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
System.out.println("去重倒序" + collect1);

打印结果
去重正序[25, 32, 50, 98]
去重倒序[98, 50, 32, 25]
排序可以自定义比较器
Comparator.comparing(OrDishwasherTemp::getProductCode)

根据 List中 Object N个属性去重

方法一:

List<Person> persons = new ArrayList<>();
persons.add(new Person("张三", 12,"4444"));
persons.add(new Person("李四", 13,"234"));
persons.add(new Person("张三", 14,"4444"));
persons.add(new Person("王五", 15,"4555"));
Map<String, Person> uniquePersons = persons.stream()
        .collect(Collectors.toMap(person -> person.getName() + person.getAddress(), person -> person, (oldValue, newValue) -> newValue));
for (Person person : uniquePersons.values()) {
    System.out.println(person);
}

toMap参数说明:
第一个:生产map的key,可以用这个参数控制去重的字段维度
第二个:生产map的value
第三个:(oldValue, newValue) -> newValue 后面的值覆盖前后的值,(oldValue, newValue) -> oldValue 保留前面的值

方法二:

productDtoList = productDtoList.stream().collect(
        Collectors.collectingAndThen(Collectors.toCollection(() ->
                new TreeSet<>(Comparator.comparing(item -> item.getProductNo() +":"+ item.getProductName()))),
                ArrayList::new));

确认比较的数据类型是否实现了Comparable接口, 使用字符串拼接实现多个属性的去重

posted @ 2018-07-27 16:34  品书读茶  阅读(2510)  评论(0)    收藏  举报