HashMap和TreeMap的遍历、排序、差别
不管是做JAVA的同学还是做Android的同学,相信大家在去公司面试的时候总会被问到一些涉及集合的问题。最近正好工作的空余时间比较多,整理一下分享给大家
这里就以HashMap和TreeMap为列进行说明。
1.HashMap和TreeMap如何进行遍历
HashMap<String, String> map = new HashMap<>(); map.put("cc", "1"); map.put("aa", "3"); map.put("ee", "2"); map.put("hh", "5"); /** * 使用for循环遍历 */ for (String key : map.keySet()) { Log.e("tag", "key=" + key + ",value=" + map.get(key)); } Log.e("tag", "---------------------------------------------"); /** * Map.entrySet使用iterator遍历key和value */ Iterator<Map.Entry<String,String>> it=map.entrySet().iterator(); while (it.hasNext()){ Map.Entry<String,String> entry=it.next(); Log.e("tag", "key=" + entry.getKey() + ",value=" + entry.getValue()); } Log.e("tag", "---------------------------------------------"); /** * 通过Map.entrySet遍历key和value */ for(Map.Entry<String,String> entry:map.entrySet()){ Log.e("tag", "key=" + entry.getKey() + ",value=" + entry.getValue()); }
2.HashMap和TreeMap如何进行排序
private void sortMap(){ /** * 按照Value排序,以hashMap为列,TreeMap默认按Key排序 */ HashMap<String, String> map = new HashMap<>(); map.put("cc", "1"); map.put("aa", "3"); map.put("ee", "2"); map.put("hh", "5"); List<Map.Entry<String, String>> list = new ArrayList<>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, String>>() { @Override public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) { /** * o1.getValue() 按照value排序 o1.getKey()按照key排序 */ return o1.getValue().compareTo(o2.getValue()); } }); for (Map.Entry<String, String> entry : list) { Log.e("tag", "key=" + entry.getKey() + ",value=" + entry.getValue()); } }
3.HashMap和TreeMap有什么差别
1.HashMap是基于Hash表的结构,根据键的hashCode存储数据,TreeMap是基于红黑二叉树的结构
2.HashMap是无序的,TreepMap实现了SortMap<K,V>接口,对key进行了排序
3.HashMap允许有空键和空值,TreeMap不允许有空键和空值