@Data
@RequiredArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private String name;
private String password;
private long classId;
}
默认去重(不起作用)
public static void main(String[] args) {
List<User> list = Arrays.asList(new User(3, "a", "a1", 2), new User(2, "b", "b1", 2), new User(1, "c", "c1", 3), new User(2, "b", "b1", 1),
new User(2, "c", "c2", 4));
method1(list);
}
//默认去重(不起作用)
public static void method1(List<User> list) {
list.stream().distinct().forEach(System.out::println);
}
单属性去重
//指定单属性去重
public static void method2(List<User> list) {
list.stream()
.collect(Collectors.toMap(
User::getName, // Key is the name property
item -> item, // Value is the person object itself
(existing, replacement) -> existing // In case of duplicate keys, keep the existing value
))
.values()
.stream()
.toList().forEach(System.out::println);;
}
双属性去重(名称+密码)
list.stream()
.collect(Collectors.toMap(
item->item.getName()+item.getPassword(), // Key is the name property
item -> item, // Value is the person object itself
(existing, replacement) -> existing // In case of duplicate keys, keep the existing value
))
.values()
.stream()
.toList().forEach(System.out::println);
以此类推,如果是三个属性去重,只需要把key变为三个属性的拼接字符。
自定义去重方法
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
list.stream().filter(User.distinctByKey(user -> user.getName()+user.getPassword()))
.forEach(System.out::println);