如果要对数组中的地图进行排序,请使用SortedMap实现,如TreeMap或ConcurrentSkipListMap。这需要一个HashMaps矢量,并返回SortedMaps的一个ArrayList(一个非矢量同步和更快的集合)。
public ArrayList<SortedMap<String, String>> sortMaps(Vector<HashMap<String, String> maps) {
ArrayList<TreeMap<String, String>> returnMaps = new ArrayList<TreeMap<String, String>>();
for(HashMap<String, String> theMap : maps) {
// TreeMap is a sorted map and this will use the default String.compareTo
TreeMap<String, String> newMap = new TreeMap<String, String>();
// put all the items from the HashMap into the TreeMap, which will autosort
newMap.putAll(theMap);
returnMaps.add(newMap);
}
return returnMaps;
}
要按第一项散列图的矢量(最低键,首字母顺序排列)尝试返回行之前执行以下操作:
// this sorts the vector by first keys
Collections.sort(returnMaps, new Comparator<SortedMap<String,String>>() {
public int compare(SortedMap<String,String> a, HashMap<String,String> b) {
return a.firstKey().compareTo(b.firstKey());
}
});
或者,如果你想通过最后的关键排序(最高键,最后按字母顺序排列):
// this sorts the vector by first keys
Collections.sort(returnMaps, new Comparator<SortedMap<String,String>>() {
public int compare(SortedMap<String,String> a, HashMap<String,String> b) {
return a.lastKey().compareTo(b.lastKey());
}
});
要返回所有键的一个有序映射(将踩在脚下的任何一式两份):
public SortedMap<String, String> singledSortedMap(Vector<HashMap<String, String> maps) {
// this will end up with all the values, sorted by natural string ordering
SortedMap<String, String> returnMap = new TreeMap<String, String>();
for(HashMap<String, String> theMap : maps) {
returnMap.putAll(theMap);
}
return returnMap;
}
你需要更加精确地描述你的问题。你想排序矢量还是hashmaps的内容?你试过什么了?结果应该如何存储? – Mat 2011-04-18 13:23:01
我不明白,一个哈希映射可以有几个键。一个哈希映射放在另一个之前的标准是什么? – aioobe 2011-04-18 13:23:41
一个HashMap可以有许多键(这就是整个点),它们甚至可以拥有完全相同的键,所以你需要更加具体地了解如何对Vector进行排序。 – 2011-04-18 13:24:47