In java8, how to set the global value in the lambdas foreach block?

前端 未结 4 1510
予麋鹿
予麋鹿 2020-12-01 10:49
    public void test(){
       String x;
       List list=Arrays.asList(\"a\",\"b\",\"c\",\"d\");

       list.forEach(n->{
          if(n.equals(\"         


        
4条回答
  •  难免孤独
    2020-12-01 10:59

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

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

提交回复
热议问题