Denis Stephanov
Denis Stephanov

Reputation: 5281

Set object in lambda expression

how could I set my object to another in lambda expression? I got error

variable used in lambda expression should be final or effectively final

with following code:

public MyObj myFun(MyObj o) {
   MyObj obj = null;

   myObjList.stream().filter(o -> ...).forEach(o -> {
      // I do some stuff here

      // I need here set obj to o, but I got error
      obj = o;
   });

   return myObj; // I need return found obj or null;
}

Upvotes: 2

Views: 6256

Answers (3)

Instead of using forEach instead consider using map(o->{...}).findFirst().get() (or similar depending on your logic if no item is relevant - your null case).

In general, you should let streams finish in a collector or a selector (findFirst/findAny etc.) because that will allow you to write simpler and clearer code

Upvotes: 1

BillRobertson42
BillRobertson42

Reputation: 12883

Instead of streaming through it, you could simply iterate through it in a loop and then return the value when you find it.

The streamy sort of answer is probably to use something like findFirst.

Upvotes: 0

lexicore
lexicore

Reputation: 43709

You can't assign o to the outer variable. But you can return it as a result of you stream processing. Use map instead of forEach and return o from the mapper. Then do findAny or findFirst - this will give you an Optional<MyObj>. Finally do orElse(null) to return the found and processed object or null if none was found.

MyObj obj = myObjList
   .stream()
   .filter(o -> ...)
   .map(o -> {
       // I do some stuff here

       // I need here set obj to o, but I got error
       return o;
   })
   .findAny()
   .orElse(null);

Upvotes: 5

Related Questions