3 回答

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

TA貢獻1834條經驗 獲得超8個贊
請使用 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貢獻1818條經驗 獲得超11個贊
要反轉映射,使其不同的值成為鍵,并將其鍵添加到相應值下的集合中,請groupingBy()在映射條目上使用。原始映射中的值必須正確實現equals()并hashCode()用作新哈希表中的鍵,這一點很重要。
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())
));
}
如果你想對組進行排序,你可以創建一個專門的“下游”收集器:
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)
));
}
添加回答
舉報