2017-05-04 42 views
1

我正在使用返回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"); 
    lhm.put(10005, "Zorat"); 

注:爲 功能在其他幾項功能使用,我不能在我的代碼更改LinkedHashMap的任何其他地圖。

我也google了,並試圖使用TreeMap,它給了我們所需的結果在升序。但是,這裏的TreeMap鍵是按升序排列的,而不是值。

我的要求主要是針對數值。

如何獲取升序順序的值。

Desired Output 

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

預先感謝您!!!!

+1

可能的重複[按值排序圖](http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java) – vefthym

+0

你只是想打印它?你不希望有一個LinkedHashMap的條目按值排序? –

+0

@RobinTopper它確定如果我可以得到LinkedHashMap條目按值排序 – Tatkal

回答

2

需要在此

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); 
} 
}; 
1

你可以用流做到這一點:

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

上面會打印你想要什麼。

0

比較這個答案開始一樣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)); 
0
lhm.entrySet().stream() 
.sorted(Map.Entry.comparingByValue().reversed()) 
.collect(Collectors.toMap(Entry::getKey, Entry::getValue)); 

這將整理您的MAP按升序排列。