如何删除列表中的重复对象< MyObject>没有equals / hashcode? [英] How to remove duplicate objects in a List<MyObject> without equals/hashcode?

查看:97
本文介绍了如何删除列表中的重复对象< MyObject>没有equals / hashcode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须移除列表中的重复对象。
这个列表有对象Blog是这样的:

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

重复的对象是标题,作者,url和描述等于其他对象。



我不能改变对象。

解决方案



/ div>

如果你不能编辑类的源代码(为什么不?),那么你需要遍历列表,并根据四个标准(标题,作者,url和描述)。



为了以高效的方式做到这一点,我将创建一个新类,例如 BlogKey 包含正确实现 equals() hashCode() 的四个元素和。然后,您可以遍历原始列表,为每个构建 BlogKey ,并添加到 HashMap

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

但是最简单的事情是只需编辑 Blog的原始源代码,以便正确实现 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?

解决方案

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().

这篇关于如何删除列表中的重复对象&lt; MyObject&gt;没有equals / hashcode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆