GroupBy字符串列表

use*_*157 5 java

我有这门课:

class A {
    private List<String> keys;
    private String otherData;
    private int otherDate2;

    // getter and setters for each
}
Run Code Online (Sandbox Code Playgroud)

对于这个类,我有一个填充了一些数据的简单列表.List<A> listOfA.现在我想将此数据转换为地图.Map<String, List<A>>

目前,我们使用一堆方法以非常复杂的方式存档它.我想,我们可以通过简单的stream()操作来解决它.

我试过这个

// first
listOfA.stream()
    .collect(Colletors.groupingBy(a -> a.getKeys()))
// produces a Map<String, List<A>>     

// second
listOfA.stream()
    .flatMap(a -> a.getKeys().stream())
    .collect(Colletors.groupingBy(string -> string))
// produces a Map<String, List<String>>
Run Code Online (Sandbox Code Playgroud)

这种情况的正确方法是什么?

编辑:要清楚,我想要一个Map<String, List<A>>.

Fed*_*ner 5

你不需要流.这样更容易:

Map<String, List<A>> result = new HashMap<>();

listOfA.forEach(a -> a.getKeys().forEach(key -> 
        result.computeIfAbsent(key, k -> new ArrayList<>()).add(a)));
Run Code Online (Sandbox Code Playgroud)

这将迭代外部和内部列表并填充Map使用computeIfAbsent,如果给定键仍然没有值,则创建一个空列表,然后将A实例简单地添加到相应的列表中.