use*_*218 5 java mapping reverse java-8 java-stream
我有一个Map<String, Set<String>>我需要扭转的。这将是一个数据示例:
("AA", ("AA01", "AA02", "AA03")
("BB", ("AA01", "BB01", "BB02")
Run Code Online (Sandbox Code Playgroud)
我想获得的是一个Map<String, Set<String>>相反的关系,像这样:
("AA01", ("AA", "BB"))
("AA02",("AA"))
("AA03",("AA"))
("BB01",("BB"))
("BB02",("BB"))
Run Code Online (Sandbox Code Playgroud)
我能够做到,但使用 foreach:
private Map<String, Set<String>> getInverseRelationship(Map<String, Set<String>> mappings) {
Map<String, Set<String>> result = new HashMap<>();
mappings.entrySet().stream().forEach(record -> {
String key = record.getKey();
Set<String> itemSet = record.getValue();
itemSet.forEach(item -> {
Set<String> values = (result.containsKey(item))? result.remove(item) : new HashSet<>();
values.add(key);
result.put(item, values);
});
});
return result;
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来使用 Java 8 流 API 来做到这一点?
你可以flatMap这样使用:
Map<String, Set<String>> invertedMap = map.entrySet().stream()
.flatMap(entry -> entry.getValue().stream()
.map(v -> new AbstractMap.SimpleEntry<>(v, entry.getKey())))
.collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toSet())));
Run Code Online (Sandbox Code Playgroud)
使用SimpleEntry您可以将每个元素存储为Set条目的键,将映射的键存储为条目的值