Java8新特性 List集合根据map的key相同去重
package com.ndsoft.single; import com.alibaba.fastjson.JSON; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class JavaList8 { public static void main(String[] args) { User user1 = new User(1, "张三", "no1", 27); User user2 = new User(2, "李四", "no2", 15); User user3 = new User(3, "王五", "no1", 24); User user4 = new User(4, "赵六", "no3", 15); User user5 = new User(5, "李七", "no1", 29); User user6 = new User(6, "钱八", "no3", 18); User user7 = new User(7, "孙九", "no1", 25); User user8 = new User(8, "周八", "no2", 19); User user9 = new User(8, "周八", "no2", 19); List<User> list = new ArrayList<>(); list.add(user1); list.add(user2); list.add(user3); list.add(user4); list.add(user5); list.add(user6); list.add(user7); list.add(user8); list.add(user9); // List转map:把list里面的元素拿出来作为map的value,自己定义key // a->a, (k1,k2)->k1: 如果有重复的key就返回第一个 Map<Integer, User> map1 = list.stream().collect(Collectors.toMap(User::getId, a -> a, (k1, k2) -> k1)); // map 转 list List<User> collect = map1.entrySet().stream().map(e -> e.getValue()).collect(Collectors.toList()); collect.stream().map((p) -> { String user = JSON.toJSONString(p); return user; }).distinct().forEach(System.out::println); } } class User { private int id; private String name; private String classNo; private int age; public User() { } public User(int id, String name, String classNo, int age) { this.id = id; this.name = name; this.classNo = classNo; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClassNo() { return classNo; } public void setClassNo(String classNo) { this.classNo = classNo; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }