SortedMap接口-Map排序的用法
SortedMap接口默认使用键值默认顺序或者通过Comparator接口实现对象作为排序依据。:
public interface SortedMap
extends Map
A Map that further provides a total ordering on its keys. The map is ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time. This order is reflected when iterating over the sorted map’s collection views (returned by the entrySet, keySet and values methods). Several additional operations are provided to take advantage of the ordering. (This interface is the map analogue of SortedSet.)
// 非继承抽象方法:
Comparator super K> comparator()
Returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.
K firstKey() // 返回在当前映射中排序最低的key
Returns the first (lowest) key currently in this map.
SortedMap
Returns a view of the portion of this map whose keys are strictly less than toKey.
K lastKey() // 返回当前映射中排序最高的key
Returns the last (highest) key currently in this map.
SortedMap
Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.
SortedMap
Returns a view of the portion of this map whose keys are greater than or equal to fromKey.
// 子类:
public class TreeMap
extends AbstractMap
implements NavigableMap
——-应用TreeMap实例化SortedMap:输出指定范围的:
package com.mldn;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
public class SortedMapDemo
{
public static void main(String[] args)
{
SortedMap
sort.put(“A”, “www.k187.com”); // 放置实体
sort.put(“B”, “www.baidu.com”);
sort.put(“C”, “www.sina.com”);
sort.put(“D”, “www.google.com”);
sort.put(“E”, “www.yahoo.com”);
System.out.println(“第一个key:” + sort.firstKey()); // 获取排序最靠前的key
System.out.println(“最后一个key:” + sort.lastKey()); // 获取排序最靠后的key
System.out.println(“最后一个key对应的值:” + sort.get(sort.lastKey())); // 获取值
// 输出所有小于指定key的实体:<
System.out.println(“输出所有小于指定key的实体:”);
for (Map.Entry
{
System.out.println(me.getKey() + “–>” + me.getValue()); // 输出实体
}
// 输出所有大于指定key的实体:>=
System.out.println(“输出所有大于指定key的实体:”);
for (Map.Entry
{
System.out.println(me.getKey() + “–>” + me.getValue()); // 输出实体
}
// 输出所有介于自定义范围内的实体:>= && <
System.out.println(“输出所有介于自定义范围内的实体:”);
for (Map.Entry
{
System.out.println(me.getKey() + “–>” + me.getValue()); // 输出实体
}
}
}
/*
ubuntu@xu-desktop:~$ java com.mldn.SortedMapDemo
第一个key:A
最后一个key:E
最后一个key对应的值:www.yahoo.com
输出所有小于指定key的实体:
A–>www.k187.com
B–>www.baidu.com
输出所有大于指定key的实体:
C–>www.sina.com
D–>www.google.com
E–>www.yahoo.com
输出所有介于自定义范围内的实体:
B–>www.baidu.com
C–>www.sina.com
D–>www.google.com
*/
声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 嗅谱网
转载请注明:转自《SortedMap接口-Map排序的用法》
本文地址:http://www.xiupu.net/archives-124.html
关注公众号:
微信赞赏
支付宝赞赏