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

问题描述

  public void test(){
String x;
列表< String>列表= Arrays.asList( A, B, C, d);

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





$ b像上面的代码一样,我想设置一个变量的值在foreach块旁边,它可以工作吗?

2.为什么?

3.那么迭代器是否有序或无序?

4.我认为lamdas foreach块对于迭代器来说是很酷且简单的,但是这实际上是一个复杂的事情,而不是java 7或之前的相同工作。

解决方案

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

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

list.forEach(n - > {
if(n.equals(d))
x [0] =匹配值;
});
}

尽管团队中的功能纯粹主义者已经准备好了,然而,更好的方法是使用更多功能的方法():

  public void test(){
List< String> list = Arrays.asList(a,b,c,d);
。字符串x = list.stream()
.filter(d::等于)
.findAny()
.map(v - >匹配值 )
.orElse(null);
}


    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.Like the code above, I want to set the value of a variable beside the foreach block, can it works?

2.And why?

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

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

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中,如何设置lambda表达式的全局值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 01:22