如何从flatMap创建HashMap?

时间:2019-05-20 08:07:22

标签: java java-8 hashmap java-stream collect

我在方法参数中有两个Maps。

 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;

我想在流上重写此方法。但是,我在流收集器中有一些问题。从流到平面图中看不到返回值(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()));

1 个答案:

答案 0 :(得分:2)

在您进行flatMap通话后,您的Stream成为Stream<List<Attr>>。看来您现在失去了要用作输出Map的键的属性。

相反,我建议map内的flatMap返回包含所需键和值的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));