如何通过列表迭代和调用方法来优化迭代。

huangapple go评论55阅读模式
英文:

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&lt;ObjTest&gt; 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 -&gt; o.getField().equals(input.getField()))) {
    return methodA(input);
} else {
    return methodB(input);
}

huangapple
  • 本文由 发表于 2023年5月17日 06:48:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76267546.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定