You might want something like Java8 Stream and filter, but if I understand your question (and the answers and comments) you want to get all the MyObj matching a criteria?
In that case, equals is not the way to do it. eg:
MyObj a = ...
a.setName("A");
a.equals("A"); // returns true
"A".equals(a); // returns false!
The javadoc of equals says that:
The equals method implements an equivalence relation on non-null
object references:
- It is reflexive: for any non-null reference value x, x.equals(x) should return true.
- It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
- It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
- It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or
consistently return false, provided no information used in equals
comparisons on the objects is modified.
For any non-null reference value x, x.equals(null) should return false.
And in that case, you have a non symmetric equals (even if javadocs says it should be rather than it must be).
You can use filter, or better Java 8's Stream.
In pre Java 8, for loops, or external library such as Guava is the way to go.
The "simple" use case is the following:
List<MyObj> matching = new ArrayList<>();
for (MyObj o : list) {
if (null != o.getName() || null != o.getId()) {
matching.add(o);
}
}
This says that you have either a name defined (eg: not null), either an id.
If you need to go further, with advanced criteria, you can do that:
interface Predicate<T> {
boolean test(@Nullable T value);
}
public class Lists {
static <T> List<T> filter(List<? extends T> list, Predicate<T> predicate) {
List<MyObj> matching = new ArrayList<>();
for (MyObj o : list) {
if (predicate.test(o)) {
matching.add(o);
}
}
return matching;
}
}
And an example:
Lists.filter(listMyObj, new Predicate<MyObj>() {
public boolean test(MyObj o) {
return null != o.getName() || null != o.getId();
}
});
But you should use Guava since it does the same, and better (my example is more or less what Guava does).
As for Java 8:
myList.stream()
.filter(o -> null != o.getName() || null != o.getId())
.collect(Collectors.toList())
And I think you can do better using MyObj::getName/getId and some Function wrapper, to do the "isNull" test.
equalsandhashcodemethods ofMyObj.entity.getName().equals(searchString)andentity.getId().equals(searchId)?list.contains().