我有这个List<MyObject> list
.
MyObject
看起来像这样:
public class MyObject {
String typeOfObject;
Integer anInteger;
Integer value;
}
如何从 list
获取对象哪里typeOfObject = "objectA"
和anInteger = 1
?
我的目标是使用 value
设置许多变量的MyObject
.
我查看了Predicate
,但似乎我只能将搜索条件基于一个属性?
最佳答案
谓词可以完全执行您想要的操作,并且可以作用于您想要的任意多个属性。您只需要使用您想要测试的任何标准来实现evaluate() 方法。
public class MyPredicate implements Predicate {
private String testId;
private String otherId;
public MyPredicate(String testId,String otherId) {
this.testId = testId;
this.otherId = otherId;
}
public boolean evaluate( Object obj ) {
boolean match = false;
if( obj instanceof MyObject ) {
if( testId.equalsIgnoreCase( ((MyObject)obj).getId())
&& otherId.equalsIgnoreCase( ((MyObject)obj).getOtherId()) ) {
match = true;
}
}
return match;
}
}
因此,在您的具体情况下,评估方法将类似于:
public boolean evaluate( Object obj ) {
boolean match = false;
if( obj instanceof MyObject ) {
if( "objectA".equals( ((MyObject)obj).typeOfObject )
&& 1 == ((MyObject)obj).anInteger ) {
match = true;
}
}
return match;
}
关于java - 在具有多个对象属性的列表中搜索对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25665663/