List stream 对象 属性去重

Posted shanheyongmu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了List stream 对象 属性去重相关的知识,希望对你有一定的参考价值。

单值去重不写了,记录对象去重

随手一个对象:

@Data
@AllArgsConstructor
public class Milk {
    private Integer key;
    private String value;
}

操作:

package com.yus.util;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;
import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

public class main {
    public static void main(String[] args) {
        Milk milk0=new Milk(0,"a");
        Milk milk1=new Milk(1,"b");
        Milk milk2=new Milk(0,"c");
        List<Milk> list=new ArrayList<>();
        list.add(milk0);
        list.add(milk1);
        list.add(milk2);
        //去重
        List<Milk> uniqueMilk = list.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(comparing(n->n.getKey()))),ArrayList::new)
        );

        for (Milk m:uniqueMilk) {
            System.out.println(m.toString());
        }

    }
}

操作底层是set,视图,collection...一堆东西,还是有点意思的,不记录了,有兴趣可深入

 

任何Object类型去重...~

 

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class TestMain {

    public static void main(String[] args) {

        List<Map<String, Object>> list = new ArrayList<>();

        Map<String, Object> map = new HashMap<>();
        map.put("id", "11");
        map.put("orderno", "No.1");
        list.add(map);

        Map<String, Object> map1 = new HashMap<>();
        map1.put("id", "2222");
        map1.put("orderno", "No.2");
        list.add(map1);

        Map<String, Object> map2 = new HashMap<>();
        map2.put("id", "33");
        map2.put("orderno", "No.2");
        list.add(map2);

        Map<String, Object> map3 = new HashMap<>();
        map3.put("id", "444");
        map3.put("orderno", "No.1");
        list.add(map3);


        Map<Object, List<Map<String, Object>>> map0 = list.stream().collect(Collectors.groupingBy(e -> e.get("orderno")));

        List<Map<String, Object>> collect = list.stream().filter(distinctByKey(n -> n.get("orderno")))
                .collect(Collectors.toList());

        collect.forEach(System.out::println);
    }

    private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        ConcurrentHashMap<Object, Boolean> map = new ConcurrentHashMap<>();
        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}

 

以上是关于List stream 对象 属性去重的主要内容,如果未能解决你的问题,请参考以下文章

Java8 list根据对象某个属性去重

java8 List去重

stream 根据指定属性去重

如何根据对象的属性去重?JDK 8 Stream 轻松搞定(来长长见识)

lambda去重

JDK8 Stream操作 collectingAndThen:根据对象的属性去重