Set object in lambda expression

删除回忆录丶 提交于 2021-02-08 03:34:10

问题


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;
}

回答1:


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);



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/47022628/set-object-in-lambda-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!