Java List.contains(字段值等于x的对象) [英] Java List.contains(Object with field value equal to x)
问题描述
我想检查 List
是否包含具有特定值的字段的对象。现在,我可以使用循环来检查,但我很好奇是否有更多的代码有效。
I want to check whether a List
contains an object that has a field with a certain value. Now, I could use a loop to go through and check, but I was curious if there was anything more code efficient.
类似的东西;
if(list.contains(new Object().setName("John"))){
//Do some stuff
}
我知道上面的代码没有做任何事情,只是为了大致证明我想要实现的目标。
I know the above code doesn't do anything, it's just to demonstrate roughly what I am trying to achieve.
另外,为了澄清,我不想使用简单循环的原因是因为此代码当前将进入循环内循环内部的循环。为了便于阅读,我不想继续为这些循环添加循环。所以我想知道是否有任何简单的(ish)替代品。
Also, just to clarify, the reason I don't want to use a simple loop is because this code will currently go inside a loop that is inside a loop which is inside a loop. For readability I don't want to keep adding loops to these loops. So I wondered if there were any simple(ish) alternatives.
推荐答案
Streams
如果您使用的是Java 8,也许您可以尝试这样的事情:
Streams
If you are using Java 8, perhaps you could try something like this:
public boolean containsName(final List<MyObject> list, final String name){
return list.stream().filter(o -> o.getName().equals(name)).findFirst().isPresent();
}
或者,您可以尝试这样的事情:
Or alternatively, you could try something like this:
public boolean containsName(final List<MyObject> list, final String name){
return list.stream().map(MyObject::getName).filter(name::equals).findFirst().isPresent();
}
此方法将返回 true
如果 List< MyObject>
包含 MyObject
,其名称为 name
。如果要对每个 MyObject
执行 getName()。equals(name)
的操作,则你可以尝试这样的事情:
This method will return true
if the List<MyObject>
contains a MyObject
with the name name
. If you want to perform an operation on each of the MyObject
s that getName().equals(name)
, then you could try something like this:
public void perform(final List<MyObject> list, final String name){
return list.stream().filter(o -> o.getName().equals(name)).forEach(
o -> {
//...
}
);
}
其中 o
代表一个 MyObject
实例。
这篇关于Java List.contains(字段值等于x的对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!