Sorting LinkedHashMap
List<Map.Entry<String, Integer>> entries =
new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b){
return a.getValue().compareTo(b.getValue());
}
});
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
This is now quite a bit easier with Java 8 streams: you don't need the intermediate map to sort:
map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.forEach(entry -> ... );
LinkedHashMap
just maintains insertion order. If you want to sort based on value, you may need to write your own comparator
.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;
public class HashMapTest {
public static void main(String[] args) {
Map<String, Integer> map=new LinkedHashMap<String, Integer>();
map.put("a", 11);
map.put("B", 12);
map.put("c", 3);
map.put("d", 4);
map.put("e", 5);
map.put("f", 6);
map.put("g", 7);
map.put("h", 8);
map.put("i", 9);
map.put("j", 3);
map.put("k", 2);
map.put("l", 1);
List<Map.Entry<String, Integer>> entries = new
ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entries,new CustomizedHashMap());
Map<String, Integer> sortedMap = new LinkedHashMap<String,
Integer>();
for (Map.Entry<String, Integer> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
System.out.print( sortedMap.put(entry.getKey(),
entry.getValue())+" ");
}
}
}
class CustomizedHashMap implements Comparator<Map.Entry<String, Integer>> {
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
// TODO Auto-generated method stub
return -o1.getValue().compareTo(o2.getValue());
}
}