1. Map集合的四种遍历方式
- 使用Map.Entry遍历
for(Map.Entry<String,String> entry : map.entrySet()){ System.out.println(entry.getKey() + "--" + entry.getValue()); }
- 使用两个foreach遍历
for(String str : map.keySet()){ System.out.println(str); } for(String str : map.values()){ System.out.println(str); }
- 使用两个iterator遍历
Iterator<Map.Entry<String, String>> entrys = map.entrySet().iterator(); while (entrys.hasNext()) { Map.Entry<String, String> entry = entrys.next(); System.out.println(entry.getKey() + "--" + entry.getValue()); }
- 使用Java8 的功能
map.forEach((key,value) -> { System.out.println(key +" -- " + value); });
2. Map排序
Java中的Map实现类包括了四种,分别是HashMap、TreeMap、HashTable、LinkedHashMap
下面只介绍TreeMap和HashMap两种实现类的排序方法
-
TreeMap排序
按照Key排序
TreeMap(Java8中默认红黑树实现,emmm需要仔细研究研究红黑树的原理与实现!)默认是按Key升序的,但若要实现其降序,需要在创建参数的时候,传入Comparator接口的实现类并重写compara方法Map<String,String> map = new TreeMap<String, String>(new Comparator<String>() { // o2.compataTo(o1),为降序,反之为升序 @Override public int compare(String o1, String o2) { return o2.compareTo(o1); } });
按照Value排序
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()); } }); for (Entry<String, String> entry : list) { System.out.println(entry.getKey() + "--" + entry.getValue()); }
-
HashMap排序 (同上~)