一、根据对象中属性去重
@Test
public void listRemoveDuplication() {
List<User> users = new ArrayList<>();
users.add(new User(1L, "aa", "aa"));
users.add(new User(1L, "aa", "bb"));
users.add(new User(1L, "aa", "cc"));
users = users.stream().collect(
collectingAndThen(
toCollection(
() -> new TreeSet<>(Comparator.comparing(User::getId))), ArrayList::new
)
);
for (User user : users) {
System.out.println(user);
}
}

二、根据对象中多个属性去重
@Test
public void listRemoveDuplication2() {
List<User> users = new ArrayList<>();
users.add(new User(1L, "aa", "aa"));
users.add(new User(1L, "aa", "bb"));
users.add(new User(1L, "aa", "cc"));
users = users.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(
() -> new TreeSet<>(
Comparator.comparing(
o -> o.getId()
+ ";"
+ o.getPwd()
)
)
), ArrayList::new
)
);
for (User user : users) {
System.out.println(user);
}
}

三、java8 去除重复字符串
@Test
public void stringRemoveDuplication() {
List<String> strings = new ArrayList<>();
strings.add("aa");
strings.add("aa");
strings.add("bb");
strings.add("cc");
strings = strings.stream().distinct().collect(Collectors.toList());
for (String str : strings) {
System.out.println(str);
}
}
