如何从 flatMap 创建 HashMap?

How create HashMap from flatMap?

我在方法参数中有两个地图。

 private Map<String, List<Attr>> getPropAttr(Map<String, List<Attr>> redundantProperty,
                                                                       Map<String, List<Attr>> notEnoughProperty) {
        Map<String, List<Attr>> propAttr = new HashMap<>();
        redundantProperty.forEach((secondPropertyName, secondPropertyAttributes) -> notEnoughProperty.entrySet().stream()
                .filter(firstPropertyName -> secondPropertyName.contains(firstPropertyName.getKey()))
                .forEach(firstProperty -> {
                    List<Attr> firstPropertyAttrs = firstProperty.getValue();
                    List<Attr> redundantPropAttrs = getRedundantPropAttrs(secondPropertyAttrs, firstPropertyAttrs);

                    String propName = firstProperty.getKey();
                    propAttr.put(propertyName, redundantPropAttrs);
                }));
        return propAttr;

我想在流中重写这个方法。但是,我在流收集器中遇到了一些问题。它没有看到 return value(List ) 从流到平面图中。在下面 - 我尝试在流 API 上重写此方法。如何在 collect(toMap(first::get, second::get)) 中设置第二个参数? 谢谢你的进步。

private Map<String, List<Attr>> getPropAttr(Map<String, List<Attr>> redundantProperty,
                                                                       Map<String, List<Attr>> notEnoughProperty) {
    return redundantProperty.entrySet().stream()
            .flatMap(secondProperty -> notEnoughProperty.entrySet().stream()
                    .filter(firstPropertyName -> secondProperty.getKey().contains(firstPropertyName.getKey()))
                    .map(firstProperty -> {
                        List<Attr> onlinePropertyAttrs = firstProperty.getValue();
                        List<Attr> redundantPropAttrs = 
                                getRedundantPropAttrs(secondProperty.getValue(), firstPropertyAttrs);
                        return redundantPropertyAttrs;
                    }))
            .collect(toMap(Property::getName, toList()));

在你的 flatMap 调用之后,你的 Stream 变成了 Stream<List<Attr>>。此时您似乎丢失了要用作输出 Map 键的 属性 。

相反,我建议 flatMap return 中的 map 包含所需键和值的 Map.Entry

return redundantProperty.entrySet()
                       .stream()
                       .flatMap(secondProperty ->
                           notEnoughProperty.entrySet()
                                            .stream()
                                            .filter(firstPropertyName -> secondProperty.getKey().contains(firstPropertyName.getKey()))
                                            .map(firstProperty -> {
                                                List<Attr> redundantPropAttrs = ...
                                                ...
                                                return new SimpleEntry<String,List<Attr>>(firstProperty.getKey(),redundantPropertyAttrs);
                                            }))
                       .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));