Search code examples
javalambdajava-streamrefactoring

How to rewrite a Java for loop which returns a matching element using streams


I would like to optymalize my method.

I have list of objects and I would like to iter by them, compare fields with input and in case of match I would like to use that first object in other method. Something like:

for (ObjTest objTest : listOfObjTest) {
    if (objTest.getField().equals(input.getField()) {
       return methodA(input, objTest);
    }
}
return methodB(input);

I was trying to do it with findFirst but I do not know how to call that

listOfObjTest.stream().filter(obj -> Objects.equals(objTest.getField(), input.getField())).findFirst().get();

Do you recommend any tutorial for lambdas and streams becouse I have a lot of problems when I have to create something new...


Solution

  • I recommend Java 8 Lambdas by O'Reilly Media.
    https://www.oreilly.com/library/view/java-8-lambdas/9781449370831/

    It offers a wealth of information, including the topic your discussing.