First of all, override the equals and hashCode methods in the Employee class, as follows
@Override public boolean equals(Object other) { if(this == other) return true; if(other == null || (this.getClass() != other.getClass())){ return false; } Employee guest = (Employee) other; return Objects.equals(guest.name, name) && Objects.equals(guest.position, position) && Objects.equals(guest.salary, salary); } @Override public int hashCode() { return Arrays.hashCode(new Object[] { name, position, salary }); }
Then you can use the Stream API distinct method to remove duplicates
Returns a stream consisting of individual elements (according to Object.equals (Object)) of this stream.
You can do it like this
Employee e1 = new Employee("John", "developer", 2000); Employee e2 = new Employee("John", "developer", 2000); Employee e3 = new Employee("Fres", "designer", 1500); Employee[] allEmployees = new Employee[100]; allEmployees[0] = e1; allEmployees[1] = e2; allEmployees[2] = e3; allEmployees = Arrays.asList(allEmployees).stream().distinct() .toArray(Employee[]::new); Arrays.asList(allEmployees).forEach(System.out::println);
Exit: (saving both empty and non-empty entries)
John developer 2000.0 Fres designer 1500.0 null
source share