I have to remove duplicated objects in a List. It is a List from the object Blog that looks like this:
public class Blog {
private String title;
priv
It is recommended to override equals() and hashCode() to work with hash-based collections, including HashMap, HashSet, and Hashtable, So doing this you can easily remove duplicates by initiating HashSet object with Blog list.
List blogList = getBlogList();
Set noDuplication = new HashSet(blogList);
But Thanks to Java 8 which have very cleaner version to do this as you mentioned you can not change code to add equals() and hashCode()
Collection uniqueBlogs = getUniqueBlogList(blogList);
private Collection getUniqueBlogList(List blogList) {
return blogList.stream()
.collect(Collectors.toMap(createUniqueKey(), Function.identity(), (blog1, blog2) -> blog1))
.values();
}
List updatedBlogList = new ArrayList<>(uniqueBlogs);
Third parameter of Collectors.toMap() is merge Function (functional interface) used to resolve collisions between values associated with the same key.