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

后端 未结 21 1671
渐次进展
渐次进展 2020-12-03 02:53

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         


        
21条回答
  •  广开言路
    2020-12-03 03:17

    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.

提交回复
热议问题