简体   繁体   English

Java 8组映射按键

[英]Java 8 group map by key

I want to group a map object by key. 我想按键对地图对象进行分组。 I try with this code but i have a compile error: 我尝试使用此代码,但出现编译错误:

Non-static method cannot be referenced from a static context

My code: 我的代码:

Map<String, List<A>> getAMap() {        
    return Arrays.stream(SomeArray.values())
            .map(map -> createObject())
            .collect(Collectors.groupingBy(Map.Entry::getKey, 
                  Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
}


private Map<String, A> createObject() 
    final A a = new A(some attributes);
    Map<String, A> map = new LinkedHashMap<>();
    map.put(some key, a);
    .... // add another values. 
    return map;
}

I need something like 我需要类似的东西

{
"a", {a1, a2, a3},
"b", {a4, a5, a6},
}

It looks like your code is wrong on some levels and that error message is not what exactly happens. 看起来您的代码在某些级别上是错误的,并且该错误消息并非确切发生的情况。

For example createObject() returns a Map so you get a Stream<Map<...>> , so obviously .collect(Collectors.groupingBy(Map.Entry::getKey... will not work. You need to change your code a bit for this to work: 例如, createObject()返回一个Map因此您得到Stream<Map<...>> ,因此显然.collect(Collectors.groupingBy(Map.Entry::getKey...将不起作用。您需要更改代码一点点的工作:

Arrays.stream(someArray)
            .flatMap(map -> createObject().entrySet().stream())
            .collect(Collectors.groupingBy(Entry::getKey,
                    Collectors.mapping(Entry::getValue, Collectors.toList())));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM