java 以相反的顺序将 collect 流式传输到 TreeMap
java Stream collect to TreeMap in reverse order
我有以下代码从流中收集地图,并将其转换为树形图
Map<String, String> result = myMap.values().stream().collect(Collectors.toMap(Person::getScore, Person::getName));
return new TreeMap<>(result);
有什么方法可以 return 在同一行中使用降序排序的 treeMap?我不能将比较器作为参数传递。
您可以使用sorted
和Comparator
并使用LinkedHashMap
收集如下,
Map<String, String> result = myMap.values().stream()
.sorted(Comparator.comparing(Person::getScore, Comparator.reverseOrder()))
.collect(Collectors.toMap(Person::getScore, Person::getName, (x, y) -> x,LinkedHashMap::new));
我建议使用 int
作为分数,因为 String 会在词法上进行比较。所以你的结果图将是 Map<Integer, String>
.
希望对您有所帮助。
我认为您可以使用 returns 收集器的四参数 toMap
方法。假设 getScore
方法 returns 和 Integer
(或者你可以继续使用 String
,但我认为它不太可用):
//supplier of TreeMap with your custom comparator
Supplier<TreeMap<Integer, String>> myMapSupplier = () -> new TreeMap<>(Comparator.reverseOrder());
Map<Integer, String> result = myMap.values()
.stream()
.collect(Collectors.toMap(Person::getScore, Person::getName, (s, s2) -> s, myMapSupplier));
最后一个元素是 Map
的供应商。正如 documentation 所述:
mapSupplier - a function which returns a new, empty Map
into which the results will be inserted
因此,您仍然可以在一次调用中获得带有自定义 Comparator
的 TreeMap
。
我有以下代码从流中收集地图,并将其转换为树形图
Map<String, String> result = myMap.values().stream().collect(Collectors.toMap(Person::getScore, Person::getName));
return new TreeMap<>(result);
有什么方法可以 return 在同一行中使用降序排序的 treeMap?我不能将比较器作为参数传递。
您可以使用sorted
和Comparator
并使用LinkedHashMap
收集如下,
Map<String, String> result = myMap.values().stream()
.sorted(Comparator.comparing(Person::getScore, Comparator.reverseOrder()))
.collect(Collectors.toMap(Person::getScore, Person::getName, (x, y) -> x,LinkedHashMap::new));
我建议使用 int
作为分数,因为 String 会在词法上进行比较。所以你的结果图将是 Map<Integer, String>
.
希望对您有所帮助。
我认为您可以使用 returns 收集器的四参数 toMap
方法。假设 getScore
方法 returns 和 Integer
(或者你可以继续使用 String
,但我认为它不太可用):
//supplier of TreeMap with your custom comparator
Supplier<TreeMap<Integer, String>> myMapSupplier = () -> new TreeMap<>(Comparator.reverseOrder());
Map<Integer, String> result = myMap.values()
.stream()
.collect(Collectors.toMap(Person::getScore, Person::getName, (s, s2) -> s, myMapSupplier));
最后一个元素是 Map
的供应商。正如 documentation 所述:
mapSupplier - a function which returns a new, empty
Map
into which the results will be inserted
因此,您仍然可以在一次调用中获得带有自定义 Comparator
的 TreeMap
。