英文:
How to optymalize iteration by list and calling method
问题
I would like to optimize my process of iteration by using a list and filtering it.
For example:
I have a short list of similar objects where the difference will be one field:
List<ObjTest> objects = getListOfObjects();
Next, I would like to check if the list is not empty and iterate through each object, compare fields with input, and if the fields match, I would like to call methodA. Otherwise, when the fields of objects do not match, I would like to call methodB.
Something like:
for (ObjTest objTest : objects) {
if (objTest.getField().equals(input.getField())) {
return methodA(input);
}
}
return methodB(input)
Is it possible to do this with objects.stream?
英文:
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?
答案1
得分: 1
你可以使用 anyMatch()
:
if (objects.stream().anyMatch(o -> o.getField().equals(input.getField()))) {
return methodA(input);
} else {
return methodB(input);
}
英文:
You can use anyMatch()
:
if (objects.stream().anyMatch(o -> o.getField().equals(input.getField()))) {
return methodA(input);
} else {
return methodB(input);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论