我正在尝试解析对包含大量数据(1000K)的地图进行排序。 有没有比这更有效的方法来排序这些地图? 下面是代码片段。
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());
}}
);
答案 0 :(得分:1)
IMO优先级队列也是一种很好的方法:
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());
}
Google Guava也是一个不错的选择,因为它提供了可以反转的BiMap实现,然后只对倒置的地图键进行排序。
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 );