3 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超6個(gè)贊
使用Collectors.groupingBy
,您可以生成從鍵到值列表的映射,前提是您可以根據(jù)值計(jì)算鍵?;蛘?,您可以使用Collectors.toMap
,前提是您可以從上游元素計(jì)算 Key 和 Value。您可能需要帶有合并功能的 toMap 版本,因?yàn)檫@將允許您處理具有相同值的多個(gè)鍵(通過將它們放在一個(gè)列表中)。
編輯:如果您想要排序,則toMap和groupingBy
的重載允許您提供 mapFactory (?) ,例如。Supplier<Map>
TreeMap::new

TA貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊
請(qǐng)使用 Collectors.groupBy() 查找以下代碼:
List<Details> employeeList = Arrays.asList(new Details("Pratik", "Developer"), new Details("Rohit", "Manager"), new Details("Sonal", "Developer"), new Details("Sagar", "Lead"), new Details("Sanket", "Lead"));
Map<String, List<Details>> collect = employeeList.stream().collect(Collectors.groupingBy(x-> x.getDesignation()));
System.out.println("Checking details "+ collect);

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超11個(gè)贊
要反轉(zhuǎn)映射,使其不同的值成為鍵,并將其鍵添加到相應(yīng)值下的集合中,請(qǐng)groupingBy()在映射條目上使用。原始映射中的值必須正確實(shí)現(xiàn)equals()并hashCode()用作新哈希表中的鍵,這一點(diǎn)很重要。
static <K, V> Map<V, Set<K>> invert(Map<? extends K, ? extends V> original) {
return original.entrySet().stream()
.collect(Collectors.groupingBy(
Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey, Collectors.toSet())
));
}
如果你想對(duì)組進(jìn)行排序,你可以創(chuàng)建一個(gè)專門的“下游”收集器:
static <K, V> Map<V, SortedSet<K>> invert(
Map<? extends K, ? extends V> original,
Comparator<? super K> order) {
Collector<K, ?, SortedSet<K>> toSortedSet =
Collectors.toCollection(() -> new TreeSet<>(order));
return original.entrySet().stream()
.collect(Collectors.groupingBy(
Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey, toSortedSet)
));
}
添加回答
舉報(bào)