的Java 8:迭代列表和添加项目到新地图
问题描述:
如何我可以在Java 8编写代码?的Java 8:迭代列表和添加项目到新地图
for (Iterator<RecordVo> iterator = list.iterator(); iterator.hasNext();) {
RecordVo recordVo = (RecordVo) iterator.next();
ExecutionContext singleThreadExecutionContext = new ExecutionContext();
singleThreadExecutionContext.put("customerId", recordVo.getCustomerId());
singleThreadExecutionContext.put("ThreadName", "Thread-"+recordVo.getCustomerId());
multiThreadExecutionContext.put("Partition - "+recordVo.getCustomerId(), singleThreadExecutionContext);
}
答
以下情况如何?
list.stream()
.map(RecordVo::getCustomerId)
.map(id -> {
// create singleThreadExecutionContext as before
return new SimpleImmutableEntry(id, singleThreadExecutionContext);
})
.forEach(e -> multiThreadExecutionContext.put("Partition - " + e.getKey(), e.getValue()))
我没有编译它,但你可以做到这一点。
+0
它编译和工作就像一个魅力。我只做了修改就是将e.getValue转换为ExecutionContext。 。 '(ExecutionContext)e.getValue()'我在我的代码中使用旧的方式,但知道如何在Java 8中执行它真的很有帮助。感谢Abhijit。 –
你为什么需要?这段代码有什么问题? –
我正在学习Java8并试图将我现有的代码修改为8个lambda。被困在这段代码中。我尝试使用流,收集,收集器,但无法前进 –
看到,学习工具意味着还要学习该工具在哪里有用以及哪里不是。在这种情况下,流不是一个有用的工具。您可以通过使用'为获得更为里程(每个:ofList)'这里比从流,这是Java的6 –