HashMap的储存是没有顺序的,而是按照key的HashCode实现.
对key排序
首先要得到HashMap中的键的集合,使用keySet,转换为数组,然后调用Arrays.sort()进行排序。
Hash Map:
——Set keySet() —— 返回一个 Set的关键视图包含在这个Map。
Set:
——Object[ ] toArray() ——返回一个包含此集合中所有元素的数组。
—— T[ ] toArray(T[ ] a) ——返回包含此集合中的所有元素的数组;返回的数组的运行时类型是指定的数组的运行时类型。
public class Test {
public static void main(String[] args) {
HashMap<Integer, Integer> map = new HashMap<>();
map.put(1, 985);
map.put(2, 211);
map.put(3, 4);
map.put(8, 9);
map.put(7, 6);
//--------------
Set set = map.keySet();
Object[] arr = set.toArray();
Arrays.sort(arr);
for (Object key : arr) {
System.out.print(key + " ");
}
}
}
对value排序
首先需要得到HashMap中的包含映射关系的视图(entrySet),entrySet转换为List,然后重写比较器比较。
那么什么是entrySet呢?
- 由于Map中存放的元素均为键值对,故每一个键值对必然存在一个映射关系。
- Map中采用Entry内部类来表示一个映射项,映射项包含Key和Value
- Map.Entry里面包含getKey()和getValue()方法,可使用它对map进行遍历。
Set<Map.Entry<K,V>> entrySet() ——返回一个 Set视图的映射包含在这个Map。
法一:list.sort();
// 对value排序
List<Map.Entry<Integer, Integer>> list = new ArrayList<Map.Entry<Integer, Integer>>(map.entrySet());
list.sort(new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
// 两种return方式
return o1.getValue().compareTo(o2.getValue());
// return o1.getValue() - o2.getValue();
}
});
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getKey() + " :" + list.get(i).getValue());
}
法二:Collections.sort()
// 对value排序
List<Map.Entry<Integer, Integer>> list = new ArrayList<Map.Entry<Integer, Integer>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
// TODO Auto-generated method stub
return o1.getValue().compareTo(o2.getValue());
}
});
for (Map.Entry<Integer, Integer> temp : list) {
System.out.println(temp.getKey() + ": " + temp.getValue());
}
反思
我之前看到map有toarray()这个函数,刚去查看了一下API,发现是我眼花了,再说了,map是key-value,转换为数组,数组怎么存储呀?
list也有相同的方法:
Object[] toArray() ——返回一个数组,包含在这个列表中的所有元素在适当的顺序(从第一个到最后一个元素)。
T[] toArray(T[] a) ——返回一个数组,包含在这个列表中的所有元素在适当的顺序(从第一到最后一个元素);返回数组的运行时类型是指定的数组的运行时类型。
之前一直都没有搞清楚这个toArray()函数,以为随随便便就可以转换,原来是我没有好好看API文档,所以瞎搞了一出。
参考博客
end.