我有这门课:
class A {
private List<String> keys;
private String otherData;
private int otherDate2;
// getter and setters for each
}
对于这门课,我有一个包含一些数据的简单列表。 List<A> listOfA
.
现在我想将此数据转换为 map 。 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>>
对于这种情况,正确的做法是什么?
编辑:明确地说,我想要一个 Map<String, List<A>>
.
最佳答案
为此您不需要流。这样更容易:
Map<String, List<A>> result = new HashMap<>();
listOfA.forEach(a -> a.getKeys().forEach(key ->
result.computeIfAbsent(key, k -> new ArrayList<>()).add(a)));
这将迭代外部和内部列表并使用 computeIfAbsent
填充 Map
,如果给定键仍然没有值,则创建一个空列表,然后 A
实例只是添加到相应的列表中。
关于java - GroupBy 字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52278322/