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)]