Remove duplicates from list of user-defined class objects in Java
Let’s say we have a User class with the following properties:
id(this is unique for each user)name
class User {
int id;
String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
}
Now suppose we created a duplicate User object and added it to the list of users. In this case, we can override the Object.equals and Object.hashCode method of the User class and call the distinct method on the users list. The distinct method internally calls the Object’s equals method to check for the equality of the objects and return a stream of distinct elements.
Code
import java.util.Objects;class User {int id;String name;public User(int id, String name) {this.id = id;this.name = name;}@Overridepublic boolean equals(Object obj) {if (this == obj) {return true;}if (obj == null) {return false;}if (getClass() != obj.getClass()) {return false;}User user = (User) obj;return id == user.id;}@Overridepublic int hashCode() {return Objects.hash(id);}}
In the code above, we have:
- Created a
Userclass with theidandnameproperties. - Overriden the
equalsmethod to implement our custom equality checking logic. We have also overridden the . If we overridehashCodehashCode() returns an integer that represents the current instance of the class. equals(), we must also overridehashCode().
import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Objects;import java.util.stream.Collectors;class RemoveDupilcate {public static void main( String args[] ) {ArrayList<User> users = new ArrayList<>();User user1 = new User(10, "Jaga");User user2 = new User(10, "Jaga");users.add(user1);users.add(user2);System.out.println("List with Duplicates");System.out.println(users);List<User> uniqueUser = users.stream().distinct().collect(Collectors.toList());System.out.println("List without Duplicates");System.out.println(uniqueUser);}}
In the code above, we have:
-
Created two objects for the
Userclass with id10, and added them to a listusers. -
Overridden
equalsandhashCodein theUserclass to check for the equality for the object. -
Removed the duplicate object from the
userslist by calling thedistinctmethod. Thedistinctmethod will internally call theequalsmethod of theuserobject to check if two objects are the same. Thedistinctmethod returns a stream of distinct objects. -
Collected the stream of a distinct object in a list with the
collectmethod. We have passedCollectors.toList()as an argument to signify that thecollectmethod should create a list from the stream.