【发布时间】:2019-07-02 11:32:33
【问题描述】:
我正在使用 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) 我们能做到这一点吗?
【问题讨论】: