首页 > 解决方案 > 在 Java 8 中迭代 Map 时使用 ForEach 提取多行 Lambda 表达式

问题描述

我正在使用Java 8迭代如下所示的地图forEach

Map<Integer,String> testMap = new HashMap<>();
testMap.put(1, "Atul");
testMap.put(2, "Sudeep");
testMap.put(3, "Mayur");
testMap.put(4, "Suso");

testMap.entrySet().forEach( (K)-> {         
                System.out.println("Key ="+K.getKey()+" Value = "+K.getValue());
                System.out.println("Some more processing ....");            
            }

    );

我的问题是:

1)我们如何forEach在处理地图时提取方法?

2)也就是说,里面的代码部分forEach应该被包裹在方法里面:

        System.out.println("Key ="+K.getKey()+" Value = "+K.getValue());
        System.out.println("Some more processing ....");    

3) 我理解forEach这种情况下的方法需要一个Consumer具有以下签名的功能接口 -

void accept(T t); 

4)所以我想要的是这样的:

   //declare a consumer object 
   Consumer<Map.Entry<Integer,String>> processMap = null;

  // and pass it to ForEach 
  testMap.entrySet().forEach(processMap);

5)我们能做到这一点吗?

标签: javaforeachjava-8

解决方案


我了解在这种情况下的 forEach 方法需要一个具有以下签名的消费者功能接口

forEach()确实期望 aConsumer但要处理 aConsumer你不一定需要 a Consumer。你需要的是一种尊重Consumer功能接口输入/输出的方法,即Entry<Integer,String>输入/void输出。

因此,您可以只调用一个具有以下参数的方法Entry

testMap.entrySet().forEach(k-> useEntry(k)));

或者

testMap.entrySet().forEach(this::useEntry));

使用 useEntry() 例如:

private void useEntry(Map.Entry<Integer,String> e)){        
    System.out.println("Key ="+e.getKey()+" Value = "+e.getValue());
    System.out.println("Some more processing ....");                        
}

声明Consumer<Map.Entry<Integer,String>>您传递给的 a ,forEach()例如:

Consumer<Map.Entry<Integer,String>> consumer = this::useEntry;
//...used then :
testMap.entrySet().forEach(consumer);

forEach()仅当您的消费者被设计为以某种方式可变(由客户端计算/传递或无论如何)时才有意义。
如果您不是在这种情况下并且您使用消费者,那么您最终使事情变得比实际需要的更抽象和复杂。


推荐阅读