如何将下面的内容转换为流,在构建desk对象之前,我必须查找两个Map,如果mydesksbynameMap中没有设置mydesk,我想抛出一个错误。
Map<String, MyDesk> myDesksByName = myDesks.stream()
.collect(Collectors.toMap(MyDesk::desk, Function.identity()));
Map<String, List<DeskScope>> deskScopesByName = deskScopes.stream()
.collect(Collectors.groupingBy(DeskScope::desk));
List<Desk> desks = new ArrayList<>();
for(String deskName: deskScopesByName.keySet()){
List<DeskScope> deskScopesForDeskName = deskScopesByName.get(deskName);
MyDesk myDesk = myDesksByName.get(deskName);
if(myDesk != null){
for(DeskScope deskScope: deskScopesForDeskName){
Desk deskWithScope = createDeskWithScope(myDesk, deskScope.outOfScope());
desks.add(deskWithScope);
}
} else {
LOGGER.warn("Desk {} is not setup , ignoring this desk", deskName);
}
}
正在尝试将上述内容转换为流,并按上述方式记录警告消息。但是我得到了一个桌面流列表,不知道如何记录警告消息。
List<Stream<Desk>> collect = deskScopesByName.keySet().stream()
.map(deskName ->
deskScopesByName.get(deskName).stream()
.map(ds -> createDeskWithScope(myDesksByName.get(deskName), ds.outOfScope())))
.collect(Collectors.toList());
1条答案
按热度按时间bqf10yzr1#
您的流将导致
List<Stream<Desk>>
,因为您不会像在外部流的末尾那样将内部流收集到集合中。如果你这样做,你最终会得到一个List<List<Desk>>
. 把嵌套的List
结构,你需要使用flatMap
.如果你应用这个,你会得到这样的结果: