0

我有这个List<MyObject> list

MyObject看起来像这样:

public class MyObject {

    String typeOfObject;

    Integer anInteger;

    Integer value;
}

如何从list哪里typeOfObject = "objectA"获取对象anInteger = 1

value我的目标是使用of设置许多变量MyObject

我看了看Predicate,但似乎我的搜索条件只能基于一个属性?

4

3 回答 3

1

您必须覆盖equals()hashcode()完成该操作,请参阅链接以完成该操作。

于 2014-09-04T12:45:30.383 回答
1

谓词可以完全按照您的意愿行事,并且可以对任意数量的属性起作用。您只需要使用要测试的任何标准来实现 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;
    }
于 2014-09-04T12:58:27.827 回答
1

如果您使用的是 Java 8,您可以使用filter来获取符合您的条件的元素,例如使用 lambda 表达式。您还可以实现自定义Predicate并在filter

List<MyObject> objects = Arrays.asList(
        new MyObject("foo", 1, 42), 
        new MyObject("foo", 3, 23), 
        new MyObject("bar", 3, 42), 
        new MyObject("foo", 4,  42));
List<MyObject> filtered = objects.stream()
        .filter(o -> o.typeOfObject.equals("foo") && o.value == 42)
        .collect(Collectors.toList());
System.out.println(filtered);

输出是[(foo,1,42), (foo,4,42)],使用这个测试类:

class MyObject {
    String typeOfObject;
    Integer anInteger;
    Integer value;
    public MyObject(String type, int i, int v) {
        this.typeOfObject = type;
        this.anInteger = i;
        this.value = v;
    }
    public String toString() {
        return String.format("(%s,%d,%d)", typeOfObject, anInteger, value);
    };
}
于 2014-09-04T13:10:55.400 回答