检查自定义列表是否包含项目

检查自定义列表是否包含项目

问题描述:

我有一个自定义列表并且想检查它是否包含特殊项目。该列表填充了Rowlayout对象。检查自定义列表是否包含项目

public RowLayout(String content, int number) { 
     this.content = content; 
     this.number = number; 
    } 

现在,我想检查我的List<Roalayout>包含在content一个特殊的项目 - 位置。我怎么做?

只要求.contains'就行不通。

什么我想检查:

if (!List<RowLayout>.contains("insert here"){ 
//Do something 
} 
+1

' hashCode'和'equals'做魔术;) – SomeJavaGuy

+0

@SomeJavaGuy,除非你不能更改类代码... – Eugene

+0

你有没有java-8? – Eugene

如果你可以编辑类RowLayout只是覆盖hashCodeequals您要为他们平等的一切。

如果你不能和具备Java-8例如,可以这样做:

String content = ... 
int number = ... 

boolean isContained = yourList.stream() 
     .filter(x -> x.getContent().equals(content)) 
     .filter(x -> x.getNumber() == number) 
     .findAny() 
     .isPresent(); 

可以很明显的回报例如,你有兴趣从OptionalfindAny

+0

对不起,但我是一个初学者。 “刚才重写'hashCode'和'equals'”是什么意思? – Sarius

+0

@Sarius https:// www。google.com/search?q=java+override+hashcode+and+equals&rlz=1C5CHFA_enMD720MD720&oq=java+override+hashcode+&aqs=chrome.5.69i57j69i60j0l4.6046j0j7&sourceid=chrome&ie=UTF-8 – Eugene

你只需要覆盖equalsList.contains相应地工作。 List.contains说,在文档中:

返回true当且仅当此列表包含至少一个元素e 这样
(O == NULLé== NULL:o.equals(E)) 。

你实现equals可能看起来像这样:

class RowLayout { 
    private String content; 
    private int number; 

    public boolean equals(Object o) 
    { 
     if (!(o instanceof RowLayout)) return false; 
     final RowLayout that = (RowLayout) o; 
     return this.content.equals(that.content) && this.number == that.number; 
    } 
} 

不要忘了also override hashCode,否则你的类不会在基于散列的结构,工作就像HashSet S或HashMap秒。

用法示例:

myList.contains(new RowLayout("Hello", 99)); 

一种替代Java的解决方案8,如果你只关心内容,不计较数量会做到这一点:

boolean isContained = myList.stream() 
          .map(RowLayout::getContent) 
          .anyMatch("some content"); 
+0

我什么时候我只是想chekc如果在第一个位置包含一个项目? F.E. 'myList.contains(new RowLayout(“Hello”));' – Sarius

+0

谢谢你的诚实! – Sarius

+0

@Sarius没问题。我已经添加了另一个Java 8解决方案,如果您只关心单个字段,则该解决方案更短。 – Michael