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