我在 LinkedHashMap 中使用返回键值对的函数。
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 键是按升序排列的,而不是值。
我的要求主要是值(value)观。
如何按升序获取值。
Desired Output
10003, "Args"
10002, "Heap"
10004, "Manus"
10001, "Stack"
10005, "Zorat"
提前谢谢你!!!!
最佳答案
为此你需要一个比较器
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);
}
};
关于java - 如何从 LinkedHashMap 中按升序获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43777478/