如何删除 List<MyObject> 中的重复对象没有等号/哈希码? [英] How to remove duplicate objects in a List&lt;MyObject&gt; without equals/hashcode?

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

问题描述

我必须删除列表中的重复对象.它是来自对象博客的列表,如下所示:

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;
    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.

我该怎么做?

推荐答案

如果不能编辑类的源代码(为什么不呢?),那么就需要遍历列表,根据四项比较每一项提到的标准(标题、作者、网址和描述").

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

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

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

然而,最简单的事情就是编辑Blog的原始源代码,使其正确实现equals()hashCode().

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

这篇关于如何删除 List<MyObject> 中的重复对象没有等号/哈希码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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