Java8 List<Map> 根据map对象某个字段值去重。

时间:2025-03-20 08:00:35

 1、方式一:使用TreeSet去重

      List<Map<String,String>>  dataList = dataList .stream().collect(  

Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(( o -> ("id") ))),
                        ArrayList::new)

       );

2、方式二:使用map去重

     List<Map<String,String> dataList = dataList .stream()
                .filter(distinctByKey(o -> ("id") ))
                .collect(());
   

    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> ((t), ) == null;
    }

 2.1、Map集合中put与putIfAbsent的区别

V put(K key, V value);       

V putIfAbsent(K key, V value);

这两种方法都是以key-value键值对的形式存在到map集合中,返回的都是上一次的值。 如果上次没值,直接返回null.

我们可以从map官网注释中看出:

1.使用put方法添加键值对,如果map集合中没有该key对应的值,则直接添加,并返回null;如果已经存在对应的值,则会覆盖旧值value为新的值;并返回 旧值

2.使用putIfAbsent方法添加键值对,如果map集合中没有该key对应的值,则直接添加,并返回null;如果已经存在对应的值,则value依旧为原来的值。并返回 原来的值

public class Java8StreamTest {

    public static class Book{

        private String id;

        private String name;

        public Book(String id, String name) {
             = id;
             = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
             = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
             = name;
        }

        @Override
        public String toString() {
            return "Book{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                '}';
        }
    }

    @Test
    public void testUnique(){
        List<Book> books = (new Book("1","1"),new Book("2","2"),new Book("3","3"),new Book("2","2"));

		//方式一:使用TreeSet去重
        List<Book> unique1 = ().collect(
                ((() -> new TreeSet<>((o -> ()))),
                        ArrayList::new));

        (unique1);

		//方式二:使用map去重
        List<Book> unique2 = ()
                .filter(distinctByKey(o -> ()))
                .collect(());
        (unique2);

    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        ("这个函数将应用到每一个item");
        return t -> ((t), ) == null;
    }

}