如果某个 属性 出现多次,我如何从 LinkedList 中删除项目?

How can I remove items from a LinkedList if a certain property appears several times?

我有一个 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 使用的 lectureId 的 WebCacheEvent - 这样在我的结果中每个 lectureId 只出现一次。

因此,我不能简单地使用

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

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

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

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

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 不能为空。

最简单的方法是:

LinkedList<WebCacheEvents> result = new LinkedList<WebCacheEvents>();
if(!doesContain(result, event))
result.add(event); 

public boolean doesContain(LinkedList<Integer> result, WebCacheEvents obj) {
  boolean isContained = false;
  for (WebCacheEvents data : result){
    if (data.getLectureId() == obj.getLectureId()){
      isContained = true;
      break;
    }
  }
  return isContained;
}