• Source
    1. /* package whatever; // don't place package name! */
    2.  
    3. import java.util.*;
    4. import java.lang.*;
    5. import java.io.*;
    6. import java.util.stream.*;
    7.  
    8. class Person
    9. {
    10. private int id;
    11. private String name;
    12.  
    13. public Person(String name, int id){
    14. this.name = name;
    15. this.id = id;
    16. }
    17.  
    18. @Override
    19. public boolean equals(Object obj) {
    20. if (obj == null) {
    21. return false;
    22. }
    23. if (!Person.class.isAssignableFrom(obj.getClass())) {
    24. return false;
    25. }
    26. final Person other = (Person) obj;
    27. if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
    28. return false;
    29. }
    30. if (this.id != other.id) {
    31. return false;
    32. }
    33. return true;
    34. }
    35.  
    36. @Override
    37. public int hashCode() {
    38. int hash = 3;
    39. hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0);
    40. hash = 53 * hash + this.id;
    41. return hash;
    42. }
    43.  
    44. @Override
    45. public String toString()
    46. {
    47. return "Name: " + name + " ID: " + id;
    48. }
    49. }
    50.  
    51. class Ideone
    52. {
    53. public static void main (String[] args) throws java.lang.Exception
    54. {
    55. ArrayList<Person> persons = new ArrayList<>(); //add some elements
    56. persons.add(new Person("test1",3));
    57. persons.add(new Person("test1",4));
    58. persons.add(new Person("test2",3));
    59. persons.add(new Person("test1",3));
    60. Set<Person> result = persons.stream().collect(Collectors.toSet());
    61. result.stream().forEach(System.out::println);
    62. }
    63. }