2

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;
}
14
  • 1
    So you're trying to find the last object in the list that matches the condition? If so, this could be a duplicate of this question. Commented Oct 30, 2017 at 19:13
  • 1
    You should use a collector. Commented Oct 30, 2017 at 19:13
  • 1
    no you are not allowed to do this in Java. state your actual end goal. Commented Oct 30, 2017 at 19:15
  • 1
    @DenisStephanov ok, but what should happen if there are multiple Elements that match your filter? Should it just use the first one? Or anyone? Commented Oct 30, 2017 at 19:19
  • 1
    @DenisStephanov you’re looking for findFirst. Commented Oct 30, 2017 at 19:21

3 Answers 3

5

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);
Sign up to request clarification or add additional context in comments.

7 Comments

to OP - if the logic inside “map” is more than 2-3 lines I’d extract it into another method and call that from “map”.
No harm using findAny but that’s more used when performing Parallel processing.
Thans for answer, but in "some stuff" I also need update founded object, and after update return it.
@Aominè What's "patel processing"?
Whatever updates you need to do to the object can be done after you've finished trawling through the stream.
|
1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.