Sorting 排序图<;长字符串>;按价值倒转
我有一个Sorting 排序图<;长字符串>;按价值倒转,sorting,dictionary,java-8,java-stream,Sorting,Dictionary,Java 8,Java Stream,我有一个映射图,我想使用Java8的特性按Long值的相反顺序对其进行排序。通过谷歌,我找到了提供这种解决方案的公司 Map<String, Long> sortedMap = map.entrySet().stream() .sorted(comparing(Entry::getValue)) .collect(toMap(Entry::getKey, Entry::getValue,
映射图
,我想使用Java8的特性按Long
值的相反顺序对其进行排序。通过谷歌,我找到了提供这种解决方案的公司
Map<String, Long> sortedMap = map.entrySet().stream()
.sorted(comparing(Entry::getValue))
.collect(toMap(Entry::getKey, Entry::getValue,
(e1,e2) -> e1, LinkedHashMap::new));
我必须先做一些导入才能运行原始代码吗
还有什么东西可以得到相反的顺序呢
Map<String, Long> sortedMap = map.entrySet().stream()
.sorted(Comparator.comparing(Entry::getValue).reversed())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
如中所述,当您在Comparator.comparating(Entry::getValue).reversed()中链接方法调用时,Java 8的类型推断达到了极限
相反,当使用像在Collections.reverseOrder(Comparator.comparing(Entry::getValue))
中的嵌套调用时,它会工作
当然,您可以使用static
import
s:
Map<String, Long> sortedMap = map.entrySet().stream()
.sorted(reverseOrder(comparing(Entry::getValue)))
.collect(toMap(Entry::getKey, Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
或
Map sortedMap=Map.entrySet().stream()
.sorted(按值比较(reverseOrder()))
.collect(toMap)(条目::getKey,条目::getValue,
(e1,e2)->e1,LinkedHashMap::new);
可能与@Misha重复我认为这条线索更合适。这里的问题是,使用Comparator.Comparating(Entry::getValue).reversed()
(尽管您在链接的线程中的解决方案会起作用,而且更好),类型传播不好。
The type Map.Entry does not define getValue(Object) that is applicable here
Map<String, Long> sortedMap = map.entrySet().stream()
.sorted(reverseOrder(comparing(Entry::getValue)))
.collect(toMap(Entry::getKey, Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
Map<String, Long> sortedMap = map.entrySet().stream()
.sorted(reverseOrder(comparingByValue()))
.collect(toMap(Entry::getKey, Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
Map<String, Long> sortedMap = map.entrySet().stream()
.sorted(comparingByValue(reverseOrder()))
.collect(toMap(Entry::getKey, Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));