使⽤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(
() -> new TreeSet<>(Comparatorparing(Student::getStudentName))),
ArrayList::new));
list.forEach(student -> System.out.StudentName() + ":" + StudentAge()));
// 输出:
// 张三:18
// 李四:18
⽅法⼆
@Test
public void duplicateKey() {
List<String> list = new LinkedList<>();
Collections.addAll(list, "apple", "pear", "banana", "banana");
System.out.println("原始List: " + JSON(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(list));
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。