I am trying to resolve sorting a map , which contains huge data(1000K). Is there any efficient way than this to sorting these maps ? below is the code snippet.
Map<Integer, String> myMap1 = new HashMap<Integer, String>();
Map<String,Integer> myMap2 = new HashMap< String,Integer>();
List <Entry<Integer,String>> lst1 = new ArrayList<Entry<Integer,String>>(myMap1.entrySet());
Collections.sort(lst1, new Comparator<Entry<Integer,String>>(){
@Override
public int compare(Entry e1, Entry e2)
{
return ((String) e1.getValue()).compareTo((String) e2.getValue());
}}
);
List <Entry<String,Integer>> lst2 = new ArrayList<Entry<String,Integer>>(myMap2.entrySet());
Collections.sort(lst2, new Comparator<Entry<String,Integer>>(){
@Override
public int compare(Entry e1, Entry e2)
{
return ((Integer) e1.getValue()).compareTo((Integer) e2.getValue());
}}
);
IMO a priority queue can also be a good approach:
Map<Integer, String> myMap1 = new HashMap<Integer, String>();
PriorityQueue<Entry<Integer, String>> pq = new PriorityQueue<Map.Entry<Integer,String>>(myMap1.size(), new Comparator<Entry<Integer, String>>() {
@Override
public int compare(Entry<Integer, String> arg0, Entry<Integer, String> arg1) {
return arg0.getValue().compareTo(arg1.getValue());
}
});
pq.addAll(myMap1.entrySet());
while (!pq.isEmpty()) {
System.out.println(pq.poll());
}
Also Google Guava can be a good option as it provides a BiMap implementations which can be inversed, and then just sort on inversed map keys.
Map<Integer, String> myMap1 = new HashMap<Integer, String>();
// insert values in myMap
Map<String,Integer> myMap2 = myMap1.inverse();
SortedMap<Integer, Character> sortedInversed = new TreeMap<Integer, Character>(myMap2 );