Diego Faria Diego Faria - 7 months ago 50
Java Question

How to remove duplicate objects in a List<MyObject> without equals/hashcode?

I have to remove duplicated objects in a List.
This List have the object Blog that is like this:

public class Blog {
private String title;
private String author;
private String url;
private String description;
...
}


A duplicated object is an object that have title, author, url and description equal to other object.

And i can't alter the object. I can't put new methods on it.

How do i do this?

Answer

If you can't edit the source of the class (why not?), then you need to iterate over the list and compare each item based on the four criteria mentioned ("title, author, url and description").

To do this in a performant way, I would create a new class, something like BlogKey which contains those four elements and which properly implements equals() and hashCode(). You can then iterate over the original list, constructing a BlogKey for each and adding to a HashMap:

Map<BlogKey, Blog> map = new HashMap<BlogKey, Blog>();
for (Blog blog : blogs) {
     BlogKey key = createKey(blog);
     if (!map.containsKey(key)) {
          map.put(key, blog);
     }
}
Collection<Blog> uniqueBlogs = map.values();

However the far simplest thing is to just edit the original source code of Blog so that it correctly implements equals() and hashCode().

Comments