[英]Map values in Collectors.groupingBy()
為了這個例子,讓我們假設我有一個帶有兩個屬性的簡單類型Tuple
:
interface Tuple<T, U> {
T getFirst();
U getSecond();
}
現在,我想將(first, second)
元組的集合轉換為一個映射,該映射將每個first
值映射到具有該特定first
值的元組中包含的所有second
值的集合。 方法groupSecondByFirst()
顯示了我想要的可能實現:
<T, U> Map<T, Set<U>> groupSecondByFirst(Set<Tuple<T, U>> tuples) {
Map<T, Set<U>> result = new HashMap<>();
for (Tuple<T, U> i : tuples) {
result.computeIfAbsent(i.getFirst(), x -> new HashSet<>()).add(i.getSecond());
}
return result;
}
如果輸入是[(1, "one"), (1, "eins"), (1, "uno"), (2, "two"), (3, "three")]
輸出將是{ 1 = ["one", "eins", "uno"], 2 = ["two"], 3 = ["three"] }
我想知道是否以及如何使用流框架實現這一點。 我得到的最好的是以下表達式,它返回一個包含完整元組作為值的映射,而不僅僅是它們的second
元素:
Map<T, Set<Tuple<T, U>>> collect = tuples.stream().collect(
Collectors.groupingBy(Tuple::getFirst, Collectors.toSet()));
我找到了解決方案; 它涉及Collections.mapping()
,它可以包裝收集器並在流上應用映射函數,以便為包裝的收集器提供元素:
static <T, U> Map<T, Set<U>> groupSecondByFirst(Collection<Tuple<T, U>> tuples) {
return tuples
.stream()
.collect(
Collectors.groupingBy(
Tuple::getFirst,
Collectors.mapping(
Tuple::getSecond,
Collectors.toSet())));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.