I would like to optymalize my process of iteration by list and filltering it. For example: I have a short list of some similar objects where the difference will be one field:
List<ObjTest> objects = getListOfObjects();
Next, I would like to check if list is not empty and iter by each object, compare fields with input andi if fields will match I would like to call methodA. Otherwise, when fields of objects not match I would like to call after iteration methodB.
Something like:
for (ObjTest objTest : objects) {
if (objTest.getField().equals(input.getField()) {
return methodA(input);
}
}
return methodB(input)
Is it possible to do by objects.stream?
You can use anyMatch()
:
if (objects.stream().anyMatch(o -> o.getField().equals(input.getField()))) {
return methodA(input);
} else {
return methodB(input);
}