public static List<Person> distinctByName(List<Person> list) {
return list.stream().filter(distinctByKey(Person::getName)).toList();
}
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> function) {
Map<Object, Boolean> map = new ConcurrentHashMap<>();
return item -> map.putIfAbsent(function.apply(item), Boolean.TRUE) == null;
}
List<Person> persons = new ArrayList<Person>();
persons.add(new Person("John", 11, "boy"));
persons.add(new Person("John1", 11, "boy"));
persons.add(new Person("John1", 11, "boy"));
persons.add(new Person("John1", 11, "boy"));
persons.add(new Person("John1", 11, "boy"));
persons.add(new Person("John1", 11, "boy"));
persons.add(new Person("John1", 11, "boy"));
persons.add(new Person("John1", 11, "boy "));
List<Person> people = distinctByName(persons);
System.out.println(people);
[Person(name=John, age=11, number=boy), Person(name=John1, age=11, number=boy)]
理解put和putIfAbsent的返回值
Map<Object, Boolean> map = new HashMap<>();
System.out.println(map);
Boolean value1 = map.putIfAbsent("key1", true);
System.out.println(value1);
System.out.println(map);
Boolean value2 = map.put("key2", true);
System.out.println(value2);
System.out.println(map);
Boolean value3 = map.put("key2", null);
System.out.println(value3);
System.out.println(map);
Boolean value4 = map.putIfAbsent("key2", null);
System.out.println(value4);
System.out.println(map);
Boolean value5= map.putIfAbsent("key3", true);
System.out.println(value5);
System.out.println(map);