TreeMap默认按照key得值升序排序
让TreeMap按照key值降序排列
TreeMap<String,String> map = new TreeMap<>(new comparator<String>(){
public int compare(String o1,String o2){
return o2.compareTo(o2);
}
});让TreeMap按照value值降序排列
TreeMap<String, String> map = new TreeMap<>();
List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(map.entrySet());;
Collections.sort(list,new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Entry<String, String> o1, Entry<String, String> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});遍历HashMap的三种方式
Map<Integer, Integer> hashmap = new HashMap<String, String>();
//方法一:通过 Map.keySet 遍历 key 和 value,多了个 getValue 的过程
for (String key : hashMap.keySet()) {
System.out.println("Key: " + key + " Value: " + hashMap.get(key));
}
//方法二:通过 Map.values() 遍历所有的 value,但不能遍历 key
for (String v : hashMap.values()) {
System.out.println("The value is " + v);
}
//方法三:通过 Map.entrySet 使用 iterator 遍历 key 和 value,而 iterator 又是要取出 entrySet的,相当于又多了一步。但其最大的特点是适用于一边遍历一边删除的场景。不需要用一个 set 先保存下来再删除了。
Iterator iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
System.out.println("Key: " + entry.getKey() + " Value: " + entry.getValue());
// 遍历完成后马上进行删除
iterator.remove();
}
// 方法四:通过 entrySet 进行遍历,直接遍历出key和value。对于 size 比较大的情况下,又需要全部遍历的时候,效率是最高的。
for (Map.Entry<String, String> entry : entries) {
System.out.println("testHashMap: key = " + entry.getKey() + ";value = " + entry.getValue());
}

京公网安备 11010502036488号