fork(2) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.Arrays;
  4. import java.util.List;
  5. import java.util.Map;
  6. import java.util.concurrent.ConcurrentHashMap;
  7. import java.util.function.Function;
  8. import java.util.function.Predicate;
  9. import static java.util.stream.Collectors.toList;
  10.  
  11. /* Name of the class has to be "Main" only if the class is public. */
  12. class Ideone
  13. {
  14.  
  15. public static void main(String[] args) {
  16. List<Person> listPersons = Arrays.asList(
  17. new Person(1, "person1"),
  18. new Person(1, "person5"),
  19. new Person(2, "person2"),
  20. new Person(1, "person1"),
  21. new Person(1, "person2"),
  22. new Person(1, "person1"),
  23. new Person(3, "person3")
  24. );
  25. List<Person> persons = listPersons.stream()
  26. .filter(distinctByKey(pr -> pr.getId() + " " + pr.getName()))
  27. .collect(toList());
  28.  
  29. persons.forEach(System.out::println);
  30. }
  31.  
  32. private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
  33. Map<Object, Boolean> seen = new ConcurrentHashMap<>();
  34. return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
  35. }
  36.  
  37. }
  38.  
  39. class Person {
  40.  
  41. private int id;
  42. private String name;
  43.  
  44. public Person() {
  45. }
  46.  
  47. public int getId() {
  48. return id;
  49. }
  50.  
  51. public Person(int id, String name) {
  52. this.id = id;
  53. this.name = name;
  54. }
  55.  
  56. public String getName() {
  57. return name;
  58. }
  59.  
  60. public void setName(String name) {
  61. this.name = name;
  62. }
  63.  
  64. @Override
  65. public String toString() {
  66. return "Person{" + "id=" + id + ", name=" + name + '}';
  67. }
  68.  
  69. }
Success #stdin #stdout 0.24s 33840KB
stdin
Standard input is empty
stdout
Person{id=1, name=person1}
Person{id=1, name=person5}
Person{id=2, name=person2}
Person{id=1, name=person2}
Person{id=3, name=person3}