我使用函数,它在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");注意:我不能将LinkedHashMap更改为代码中的任何其他映射,因为该函数正在其他几个函数中使用。
我也在谷歌上搜索并尝试使用TreeMap,它以升序的方式给出了我们想要的结果。但是,这里的TreeMap键是按升序排列的,而不是值。
我的要求主要是价值观。
怎样才能按升序得到值。
Desired Output
10003, "Args"
10002, "Heap"
10004, "Manus"
10001, "Stack"
10005, "Zorat"提前谢谢!
发布于 2017-05-04 08:25:25
你需要一个比较器
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);
}
};发布于 2017-05-04 08:22:30
您可以使用流来完成此操作:
lhm.entrySet().stream().sorted(Map.Entry.comparingByValue())
.forEach( (e)->System.out.println(e.getKey() + ", " + e.getValue()) );上面会印出你想要的东西。
发布于 2017-05-04 09:01:09
这个答案与this answer相同,但将排序的条目放回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));https://stackoverflow.com/questions/43777478
复制相似问题