Introduction
In this short tutorial, we'll show how to remove duplicates from List of Java Objects without overriding equals() or using hashcode() method. We'll introduce the class Item and as we can see, it contains only two fields - id and name. We'll be using field name to filter items, so when the Item has name same as existing Item it will be considered a duplicate.
Implementation
Let's first define a class called Item that we'll serve as the type of object in our List.
public class Item {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The main idea here is to use Map where we would put filtered elements. Later on, we'll convert the Map to the list free of duplicates.
private List<QueryItem> getListWithoutDuplicates(List<Item> queryItems) {
Map<String, Item> filteringMap = new HashMap<String, Item>();
for (Item item: items) {
if (filteringMap.containsKey(item.getName())) {
continue;
} else {
filteringMap.put(item.getName(), item);
}
}
return new ArrayList<Item>(filteringMap.values());
}
Conclusion
In this short tutorial, we saw one approach to how to remove duplicates from a list of Java Objects.