使用 Java 8 个流创建和反转 MultiMap
Create and Invert MultiMap w/ Java 8 Streams
如何使用 Java 8 个流或多图将 Set<Result>
转换为 Map<Item, Set<String>>
或 SetMultimap<Item, String>
,其中 Result
是:
class Result {
String name;
Set<Item> items;
}
例如,我开始于:
result1:
name: name1
items:
- item1
- item2
result2:
name: name2
items:
- item2
- item3
并以:
结尾
item1:
- name1
item2:
- name1
- name2
item3:
- name2
下面代码片段中的两个重要方法是 Stream.flatMap & Collectors.mapping:
import java.util.Map.Entry;
import java.util.AbstractMap.SimpleEntry;
import static java.util.stream.Collectors.*;
results.stream()
//map Stream<Result> to Stream<Entry<Item>,String>
.flatMap(it -> it.items.stream().map(item -> new SimpleEntry<>(item, it.name)))
//group Result.name by Item
.collect(groupingBy(Entry::getKey, mapping(Entry::getValue, toSet())));
一旦 jdk-9 中有 Collectors.flatMapping
,它看起来可能会有点不同。此外,您的 Item
实例需要在某种程度上具有可比性,或者您可以在 groupBy
中指定(比如通过字段 'itemName'):
Map<Item, Set<String>> map = results.stream()
.collect(Collectors.flatMapping(
(Result result) -> result.getItems()
.stream()
.map((Item item) -> new AbstractMap.SimpleEntry<>(item, result.getName())),
Collectors.groupingBy(Entry::getKey, () -> new TreeMap<>(Comparator.comparing(Item::getItemName)),
Collectors.mapping(Entry::getValue, Collectors.toSet()))));
如何使用 Java 8 个流或多图将 Set<Result>
转换为 Map<Item, Set<String>>
或 SetMultimap<Item, String>
,其中 Result
是:
class Result {
String name;
Set<Item> items;
}
例如,我开始于:
result1:
name: name1
items:
- item1
- item2
result2:
name: name2
items:
- item2
- item3
并以:
结尾item1:
- name1
item2:
- name1
- name2
item3:
- name2
下面代码片段中的两个重要方法是 Stream.flatMap & Collectors.mapping:
import java.util.Map.Entry;
import java.util.AbstractMap.SimpleEntry;
import static java.util.stream.Collectors.*;
results.stream()
//map Stream<Result> to Stream<Entry<Item>,String>
.flatMap(it -> it.items.stream().map(item -> new SimpleEntry<>(item, it.name)))
//group Result.name by Item
.collect(groupingBy(Entry::getKey, mapping(Entry::getValue, toSet())));
一旦 jdk-9 中有 Collectors.flatMapping
,它看起来可能会有点不同。此外,您的 Item
实例需要在某种程度上具有可比性,或者您可以在 groupBy
中指定(比如通过字段 'itemName'):
Map<Item, Set<String>> map = results.stream()
.collect(Collectors.flatMapping(
(Result result) -> result.getItems()
.stream()
.map((Item item) -> new AbstractMap.SimpleEntry<>(item, result.getName())),
Collectors.groupingBy(Entry::getKey, () -> new TreeMap<>(Comparator.comparing(Item::getItemName)),
Collectors.mapping(Entry::getValue, Collectors.toSet()))));