在java8中,如何在lambdas foreach块中设置全局值? [英] In java8, how to set the global value in the lambdas foreach block?

查看:28
本文介绍了在java8中,如何在lambdas foreach块中设置全局值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    public void test(){
       String x;
       List<String> list=Arrays.asList("a","b","c","d");

       list.forEach(n->{
          if(n.equals("d"))
            x="match the value";
       });
    }

1.像上面的代码,我想在foreach块旁边设置一个变量的值,可以吗?

1.Like the code above, I want to set the value of a variable beside the foreach block, can it works?

2.为什么?

3.foreach迭代器是有序还是无序?

3.And the foreach iterator is in order or disorder?

4.我认为 lamdas foreach 块对于迭代器来说很酷也很简单,但这确实是一件很复杂的事情,而不是在 Java 7 或更早版本中进行相同的工作.

4.I think the lamdas foreach block is cool and simple for iterator,but this is really a complicated thing to do rather than the same work in java 7 or before.

推荐答案

当然,您可以通过一个技巧使外部值可变":

You could, of course, "make the outer value mutable" via a trick:

public void test() {
    String[] x = new String[1];
    List<String> list = Arrays.asList("a", "b", "c", "d");

    list.forEach(n -> {
        if (n.equals("d"))
            x[0] = "match the value";
    });
}

不过,准备好迎接团队中功能纯粹主义者的殴打.然而,更好的是使用更实用的方法(类似于 Sleiman 的方法):

Get ready for a beating by the functional purist on the team, though. Much nicer, however, is to use a more functional approach (similar to Sleiman's approach):

public void test() {
    List<String> list = Arrays.asList("a", "b", "c", "d");
    String x = list.stream()
                   .filter("d"::equals)
                   .findAny()
                   .map(v -> "match the value")
                   .orElse(null);
}

这篇关于在java8中,如何在lambdas foreach块中设置全局值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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