與SortedSet接口類似,SortedMap也是一個結構,待排序的Map,其一個比較常用的實現類是TreeMap。
TreeMap的put(K key, V value)方法在每添加一個元素時,都會自動排序。
構造方法:
TreeMap() 使用鍵的自然順序構造一個新的、空的樹映射。 TreeMap(Comparator<? super K> comparator) 構造一個新的、空的樹映射,該映射根據給定比較器進行排序。 TreeMap(Map<? extends K,? extends V> m) 構造一個與給定映射具有相同映射關系的新的樹映射,該映射根據其鍵的自然順序 進行排序。
創建自定義的Comparator比較器:
//這里根據字符的ASCII碼大小進行降序排序: class MyComparator2 implements Comparator<String>{ @Override public int compare(String o1, String o2) { return o2.compareTo(o1); } }
在SortedSet中,當保存對象時一定要自定義一個比較器Comparator,但是在SortedMap中,保存對象卻不一定要,因為SortedMap是比較Key而不是Value,所以創建的自定義比較器也是針對Key的,比如上面創建的Comparator是針對Key類型為String的Map進行排序。
Map<String, String> map = new TreeMap<String, String>(new MyComparator2());
對於TreeMap的迭代和HashMap一樣,同樣有三種方法,以下是常用的其中一種:
Set<Map.Entry<Integer, Integer>> set = map.entrySet(); for(Iterator<Map.Entry<Integer, Integer>> iter = set.iterator(); iter.hasNext();){ Map.Entry<Integer, Integer> entry = iter.next(); Integer key = entry.getKey(); Integer value = entry.getValue(); System.out.println(key + ":" + value); }
對於Map來說,不能使用Collections的靜態方法,但是可以通過他的values方法獲取到Collections進行調用:
Collection<Integer> cols = map.values();
Integer max = Collections.max(cols);
除了文章中有特別說明,均為IT宅原創文章,轉載請以鏈接形式注明出處。
本文鏈接: http://www.itzhai.com/treemap-sortedmap-interface-implementation-class-introduction-and-implementation-of-custom-comparator-comparator.html
本文鏈接: http://www.itzhai.com/treemap-sortedmap-interface-implementation-class-introduction-and-implementation-of-custom-comparator-comparator.html