System.out.println(sortedMap2); //Collectors.toMap 直接返回排好序的map map = map.entrySet().stream() .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())) .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue(), (x1, x2) -> x2, LinkedHashMap::new)); // map ...
TreeMap会根据键的自然顺序或自定义比较器来对键进行排序。我们可以根据Map中的值来创建一个自定义比较器,从而实现按值排序。 importjava.util.*;publicclassSortMapByValue{publicstaticvoidmain(String[]args){Map<String,Integer>map=newHashMap<>();map.put("A",5);map.put("B",3);map.put("C",8);...
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) { return o2.getValue().compareTo(o1.getValue()); // 这里改为根据value值进降序排序,这里也可以改成根据key和value进行排序 } }); Map<String, String> result = new LinkedHashMap<>(); for (Map.Entry<String...
运行这段代码,你将看到Map的key-value对根据value的值进行了倒序排序并输出。
(map); //按Key进行排序 Map<String, String> resultMap = sortMapByValue(map); // 按Value进行排序 for (Map.Entry<String, String> entry : resultMap.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } } /** * 使用 Map按key进行排序 * * @param map * ...
.sorted(Map.Entry.<String,Integer>comparingByValue()) .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));System.out.println(sortedMap);//DESC Collections.reverseOrder || reversed()map.entrySet().stream() .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())) ...
[1] Sort map by value http://www.leveluplunch.com/java/examples/sort-order-map-by-values/ [2] How to sort a Map in Java http://www.mkyong.com/java/how-to-sort-a-map-in-java/ [3] Sort a Map<Key, Value> by values (Java) http://stackoverflow.com/questions/109383/sort-a-map...
.sorted(Map.Entry.comparingByKey()) .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));// map 根据value 排序 根据value 进行降序排列LinkedHashMap<String, Integer> collect2 = unsortMap.entrySet().stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) ...
util.LinkedHashMap; import java.util.Map; import static java.util.Map.Entry.comparingByValue; import static java.util.stream.Collectors.toMap; public class SortTest { public static void main(String[] args) throws Exception { // 创建一个字符串为Key,数字为值的map Map budget = new HashMap<>...
new ArrayList<>(map.entrySet()):将Set转化为List,并使用ArrayList来存储。 第二步:使用Stream对List进行排序 有了List之后,我们可以使用Java8的Stream来对其进行排序。下面是代码示例: entryList.sort(Map.Entry.comparingByValue(Comparator.reverseOrder())); ...