Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created February 17, 2013 03:25
Show Gist options
  • Save charlespunk/4969955 to your computer and use it in GitHub Desktop.
Save charlespunk/4969955 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
public class SortHashMap {
public static ArrayList<Map.Entry<String, Integer>> sortHashMapByValueWithCollections(HashMap<String, Integer> map){
ArrayList<Map.Entry<String, Integer>> al = new ArrayList<>(map.entrySet());
Collections.sort(al, new Comparator<Map.Entry<String, Integer>>(){
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2){
Integer first = o1.getValue();
Integer second = o2.getValue();
return first.compareTo(second);
}
});
return al;
}
public static TreeMap<String, Integer> sortHashMapByValueWithTreeMap(HashMap<String, Integer> map){
TreeMap<String, Integer> treeMap = new TreeMap<>(new ValueComparator(map));
treeMap.putAll(map);
return treeMap;
}
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("c", 1);
map.put("b", 2);
map.put("a", 3);
System.out.println(map);
ArrayList<Map.Entry<String, Integer>> al = sortHashMapByValueWithCollections(map);
System.out.println(al);
TreeMap<String, Integer> treeMap = sortHashMapByValueWithTreeMap(map);
System.out.println(treeMap);
}
}
class ValueComparator implements Comparator<String>{
Map<String, Integer> map;
public ValueComparator(Map<String, Integer> map){
this.map = map;
}
public int compare(String a, String b){
if(map.get(a) >= map.get(b)) return 1;
else return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment