使用Lambda给List集合去重

实体类

class Student {

    private String studentName;
    private Integer studentAge;

    public Student() {
    }

    public Student(String studentName, Integer studentAge) {
        this.studentName = studentName;
        this.studentAge = studentAge;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public Integer getStudentAge() {
        return studentAge;
    }

    public void setStudentAge(Integer studentAge) {
        this.studentAge = studentAge;
    }
}

去重

	List<Student> list = new ArrayList<>();
        Collections.addAll(list, new Student("张三", 18), new Student("李四", 18), new Student("张三", 18));
        list =
                list.stream()
                        .collect(
                                Collectors.collectingAndThen(
                                        Collectors.toCollection(
                                                () -> new TreeSet<>(Comparator.comparing(Student::getStudentName))),
                                        ArrayList::new));
        list.forEach(student -> System.out.println(student.getStudentName() + ":" + student.getStudentAge()));
		// 输出:
			// 张三:18
			// 李四:18

方法二

@Test
public void duplicateKey() {
	List<String> list = new LinkedList<>();
	Collections.addAll(list, "apple", "pear", "banana", "banana");

	System.out.println("原始List: " + JSON.toJSON(list));

	Map<String, String> map = list.stream().
			collect(Collectors.
					toMap(item -> item, item -> item, (item1, item2) -> item1));

	list.clear();
	// TODO: 使用Map集合value不可重复的特征, 给List集合去重
	map.forEach((k, v) -> list.add(v));

	System.out.println("去重List: " + JSON.toJSON(list));
}
原文地址:https://www.cnblogs.com/Twittery/p/14388009.html