检查自定义列表是否包含项目
问题描述:
我有一个自定义列表并且想检查它是否包含特殊项目。该列表填充了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
}
答
如果你可以编辑类RowLayout
只是覆盖hashCode
和equals
您要为他们平等的一切。
如果你不能和具备Java-8例如,可以这样做:
String content = ...
int number = ...
boolean isContained = yourList.stream()
.filter(x -> x.getContent().equals(content))
.filter(x -> x.getNumber() == number)
.findAny()
.isPresent();
可以很明显的回报例如,你有兴趣从Optional
从findAny
。
答
你只需要覆盖equals
为List.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");
' hashCode'和'equals'做魔术;) – SomeJavaGuy
@SomeJavaGuy,除非你不能更改类代码... – Eugene
你有没有java-8? – Eugene