java—使用流通过查找两个Map和日志警告消息来创建集合

vybvopom  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(296)

如何将下面的内容转换为流,在构建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());
bqf10yzr

bqf10yzr1#

您的流将导致 List<Stream<Desk>> ,因为您不会像在外部流的末尾那样将内部流收集到集合中。如果你这样做,你最终会得到一个 List<List<Desk>> . 把嵌套的 List 结构,你需要使用 flatMap .
如果你应用这个,你会得到这样的结果:

List<Desk> collect = deskScopesByName.keySet().stream()
        .flatMap(deskName -> deskScopesByName.get(deskName).stream()
                .map(ds -> createDeskWithScope(myDesksByName.get(deskName), ds.outOfScope()))
                .collect(Collectors.toList()))
        .collect(Collectors.toList());

相关问题