0

I have this List<MyObject> list.

MyObject looks like this :

public class MyObject {

    String typeOfObject;

    Integer anInteger;

    Integer value;
}

How to get the object(s) from list where typeOfObject = "objectA" and anInteger = 1 ?

My goal is to set many variables with value of MyObject.

I looked at Predicate, but it seems that I can base my search condition only on one attribute ?

BnJ
  • 1,024
  • 6
  • 18
  • 37

3 Answers3

1

You would have to override equals() and hashcode() to accomplish that refer this link to accomplish that.

Darshan Lila
  • 5,772
  • 2
  • 24
  • 34
  • This should be the right and clean way to do this if you want to avoid iterating over your list each time you want to get an element. – MichaelS Sep 04 '14 at 12:49
1

Predicates can do exactly what you want and can work on as many attributes as you want them to. You just need to implement the evaluate() method with whatever criteria you want to test against.

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;
    }
}

So in your specific case, the evaluate method would look something like:

    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;
    }
tokkov
  • 2,959
  • 1
  • 13
  • 9
1

If you are using Java 8, you can use filter to get the elements matching your criteria, e.g. using a lambda expression. You can also implement a custom Predicate and use that in 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);

Output is [(foo,1,42), (foo,4,42)], using this test class:

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);
    };
}
tobias_k
  • 81,265
  • 12
  • 120
  • 179