如何从 LinkedHashMap 中按升序获取值

How to get value in ascending order from LinkedHashMap

我在 LinkedHashMap 中使用 returns 键值对的函数。

LinkedHashMap<Integer,String> lhm = new LinkedHashMap<Integer,String>();

  // Put elements to the map
  lhm.put(10001, "Stack");
  lhm.put(10002, "Heap");
  lhm.put(10003, "Args");
  lhm.put(10004, "Manus");
  lhm.put(10005, "Zorat");

Note: I cannot change LinkedHashMap to any other map in my code as the function is being used in several other functions.

我还用谷歌搜索并尝试使用 TreeMap,它按升序为我们提供了所需的结果。但是,这里的 TreeMap 键是按升序排列的,而不是值。

我的要求主要是价值观。

如何获取升序排列的值。

Desired Output

10003, "Args"
10002, "Heap"
10004, "Manus"
10001, "Stack"
10005, "Zorat"

提前致谢!!!!

您可以使用流执行此操作:

lhm.entrySet().stream().sorted(Map.Entry.comparingByValue())
    .forEach( (e)->System.out.println(e.getKey() + ", " + e.getValue()) );

上面会打印出你想要的。

为此你需要一个比较器

  Comparator<Entry<String, String>> valueComparator = new 
                                  Comparator<Entry<String,String>>() { 
  @Override public int compare(Entry<String, String> e1, Entry<String, 
     String> e2) { 

     String v1 = e1.getValue(); String v2 = e2.getValue(); return 
     v1.compareTo(v2); 
 } 
};

此答案的开头与 相同,但将排序后的条目放回 LinkedHashMap:

LinkedHashMap<Integer,String> lhm2 = 
  lhm.entrySet().stream().sorted(Map.Entry.comparingByValue())
  .collect(Collectors.toMap(Entry::getKey, Entry::getValue,(a,b)->a, LinkedHashMap::new));

lhm2.forEach((k,v) -> System.out.println(k + ", " + v));
lhm.entrySet().stream()
.sorted(Map.Entry.comparingByValue().reversed())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));

这将按升序对您的 MAP 进行排序。