java - 在 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)我们能做到这一点吗?
解决方案
我了解在这种情况下的 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()
仅当您的消费者被设计为以某种方式可变(由客户端计算/传递或无论如何)时才有意义。
如果您不是在这种情况下并且您使用消费者,那么您最终使事情变得比实际需要的更抽象和复杂。
推荐阅读
- azure - 在azure上使用asp.net core 3部署vue应用程序时,nmp如何运行构建工作
- python - GEKKO 中的 MPC 模式
- arrays - 为什么我的数据没有显示在我的 TableView 中?
- r - 如何在 R 中对数据框应用 10 年平均过滤器?
- excel - 有没有办法跨行二维数组?
- discord.py - 如果消息链接包含特定字符串,如何检索它?
- android - 启动画面在每个页面上显示为背景
- scala - 使用 Spark、Scala 在查询结果的 Array 结构类型中创建自定义输出
- python - 编写函数以将列添加到数据框
- spring - 表单验证在 Spring Mvc 应用程序中不起作用