首页 > 解决方案 > 如果某个属性出现多次,如何从 LinkedList 中删除项目?

问题描述

我有一个 LinkedList,其中填充了 WebCacheEvents 类型的对象。每个对象都有描述、事件、标签、lectureId 等属性:

//filling the list with data received earlier
List<WebCacheEvents> result = new LinkedList<WebCacheEvents>();
                for (WebCache event : events) 
                    result.add(new thabella.dto.out.WebCacheEvents(event));
                return result;

我想要做的是删除任何具有已被列表中另一个 WebCacheEvent 使用的演讲 ID 的 WebCacheEvent - 这样在我的结果中每个演讲 ID 只出现一次。

因此,我不能简单地使用

if(!result.contains(event))
    result.add(event);

因为我并不是真的在寻找真正的重复项,其中 WebCacheEvent 的每个属性都具有相同的值,但仅适用于具有相同 LectureId 的对象。在我收到的事件中,可以有两个或多个具有相同的 LectureId 的对象。

是否有类似的方法可以使用“包含”方法,但仅适用于对象的某些属性?

标签: javaadd

解决方案


你可以简单地使用一个过滤器:

List<WebCacheEvents> result = new LinkedList<WebCacheEvents>();
    for (WebCache event : events)
        if (result.stream().noneMatch(w -> w.getLectureId().equals(event.getLectureId())))
            result.add(new thabella.dto.out.WebCacheEvents(event));
    return result;

我想 lecturId 不能为空。


推荐阅读