SortedMap接口扩展了映射,并确保所有条目都按升序排列(因此,SortedMap)。

如果要按降序排列它,则需要重写SortedMap中的Compare方法,我们将在稍后进行操作。TreeMap实现SortedMap,并按其自然顺序或指定的比较器对键进行排序。在TreeMap 中,不允许使用空键和空值。

方法摘要
Comparator <? super K> comparator():返回用于对当前映射中的键进行排序的比较器;如果当前映射使用其键的自然顺序,则返回null。Set<Map.Entry<K,V>> entrySet():返回当前映射中包含的映射的Set视图。K firstKey():返回映射中当前的第一个键(最低还是最高,取决于实现映射的方式(升序还是降序)。SortedMap<K,V> headMap(K toKey):返回当前映射中其键严格小于toKey的部分的视图。Set<K> keySet():返回当前映射中包含的键的Set视图K lastKey():返回映射中当前的最后一个(最高或最低)键SortedMap<K,V> subMap(K fromKey, K toKey):返回当前映射的部分视图,其有效范围从fromKey到toKeySortedMap<K,V> tailMap(K fromKey):返回当前映射中键大于或等于fromKey的部分的视图Collection <V> values():返回当前映射中包含的值的集合视图
有关这些方法的更多详细信息,请查阅官方 Oracle 文档。
代码实现
import java.util.*;public class SortedHashMapExample {public static void main(String args[]) {Map<Double, String> players = new TreeMap<Double, String>();// health, nameplayers.put(new Double(100.00), "Hill");players.put(new Double(120.00), "John");players.put(new Double(150.00), "Sabrina");players.put(new Double(105.00), "Caitlyn");players.put(new Double(110.00), "Rachel");players.put(new Double(130.00), "Michael");players.put(new Double(140.00), "Mark");// get a set of the entriesSet setOfEntries = players.entrySet();// get an iteratorIterator iterator = setOfEntries.iterator();while(iterator.hasNext()) {// create an entry of the mapMap.Entry entry = (Map.Entry)iterator.next();System.out.println("Key: " + entry.getKey());System.out.println("Value: " + entry.getValue());}}}
输出
Key: 100.0Value: HillKey: 105.0Value: CaitlynKey: 110.0Value: RachelKey: 120.0Value: JohnKey: 130.0Value: MichaelKey: 140.0Value: MarkKey: 150.0Value: Sabrina
如您所见,它将自动按升序对它们进行分组。 它的生命值从 100.00 开始,直到 150.00。 我将健康作为关键,并将名称作为值的原因只是为了向您表明它提升了他们。
但是,如果我们希望按降序排列它们怎么办?
使用降序实现
import java.util.*;public class SortedHashMapExample {public static void main(String args[]) {Map<Double, String> players = new TreeMap<Double, String>(new Comparator<Double>() {@Overridepublic int compare(Double x, Double y) {return y.compareTo(x);}});// name, healthplayers.put(new Double(100.00), "Hill");players.put(new Double(120.00), "John");players.put(new Double(150.00), "Sabrina");players.put(new Double(105.00), "Caitlyn");players.put(new Double(110.00), "Rachel");players.put(new Double(130.00), "Michael");players.put(new Double(140.00), "Mark");// get a set of the entriesSet setOfEntries = players.entrySet();// get an iteratorIterator iterator = setOfEntries.iterator();while(iterator.hasNext()) {// create an entry of the mapMap.Entry entry = (Map.Entry)iterator.next();System.out.println("Key: " + entry.getKey());System.out.println("Value: " + entry.getValue());}}}
输出
Key: 150.0Value: SabrinaKey: 140.0Value: MarkKey: 130.0Value: MichaelKey: 120.0Value: JohnKey: 110.0Value: RachelKey: 105.0Value: CaitlynKey: 100.0Value: Hill
走你,再简单不过了吧? 我们所做的只是覆盖比较方法,而不是x => y(升序),我们将其更改为y => x(降序)。
