Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从LinkedHashMap中按升序获取值_Java_Sorting_Collections_Treemap_Linkedhashmap - Fatal编程技术网

Java 如何从LinkedHashMap中按升序获取值

Java 如何从LinkedHashMap中按升序获取值,java,sorting,collections,treemap,linkedhashmap,Java,Sorting,Collections,Treemap,Linkedhashmap,我使用的函数返回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");

我使用的函数返回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");

提前谢谢你

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

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); 
 } 
};
比较器值比较器=新
比较器(){
@重写公共int比较(条目e1,条目e2){
字符串v1=e1.getValue();字符串v2=e2.getValue();返回
v1.比较(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));
LinkedHashMap 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));

这将按升序对地图进行排序。

是否可能重复您只想打印它?你不想让LinkedHashMap中的条目按值排序吗?@RobinTopper如果我可以用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));