首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从LinkedHashMap中按升序求值

如何从LinkedHashMap中按升序求值
EN

Stack Overflow用户
提问于 2017-05-04 08:19:32
回答 4查看 511关注 0票数 1

我使用函数,它在LinkedHashMap中返回键值对。

代码语言:javascript
复制
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键是按升序排列的,而不是值。

我的要求主要是价值观。

怎样才能按升序得到值。

代码语言:javascript
复制
Desired Output

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

提前谢谢!

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2017-05-04 08:25:25

你需要一个比较器

代码语言:javascript
复制
  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); 
 } 
};
票数 2
EN

Stack Overflow用户

发布于 2017-05-04 08:22:30

您可以使用流来完成此操作:

代码语言:javascript
复制
lhm.entrySet().stream().sorted(Map.Entry.comparingByValue())
    .forEach( (e)->System.out.println(e.getKey() + ", " + e.getValue()) );

上面会印出你想要的东西。

票数 1
EN

Stack Overflow用户

发布于 2017-05-04 09:01:09

这个答案与this answer相同,但将排序的条目放回LinkedHashMap中:

代码语言:javascript
复制
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));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43777478

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档