在Lambda表达式中设置对象 [英] Set object in lambda expression

查看:125
本文介绍了在Lambda表达式中设置对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将我的对象设置为lambda表达式中的另一个对象?我遇到错误

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

lambda表达式中使用的

变量应为最终变量或有效最终变量

variable used in lambda expression should be final or effectively final

具有以下代码:

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

推荐答案

您不能将o分配给外部变量.但您可以将其作为流处理的结果返回.使用map代替forEach,然后从映射器返回o.然后执行findAnyfindFirst-这将为您提供Optional<MyObj>.最后,执行orElse(null)返回找到并处理的对象;如果未找到,则返回null.

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

这篇关于在Lambda表达式中设置对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆