使用TreeMap

package collections;

import java.util.Map.Entry;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;

public class TestTreeMap {

	public static void main(String[] args) {
		// Integer实现了Comparable接口,可以作为TreeMap的key类型
		TreeMap<Integer, String> map = new TreeMap<Integer, String>();
		Random random = new Random();
		for (int i = 0; i < 10; i++) {
			int j = random.nextInt(100);
			map.put(j, "j=" + j);
		}
		map.put(50, "j=50");
		// TreeMap的迭代是有序的
		System.out.print("iterable map : ");
		printSort(map);
		System.out.println();
		// higherEntry方法会找到比指定key值稍大一点的Entry,下面的循环和上面迭代器的效率一样,没有任何区别
		for (Entry<Integer, String> entry = map.firstEntry(); entry != null; entry = map
				.higherEntry(entry.getKey())) {
			System.out.print(entry.getValue() + " ");
		}
		System.out.println();
		// ceiling找到与key相等或者更大一点的Entry
		System.out.println("ceiling 50 : " + map.ceilingEntry(50).getValue());
		System.out.println("ceiling 51 : " + map.ceilingEntry(51).getValue());
		// floor找到与key相等或者更小一点的Entry
		System.out.println("floor 50 : " + map.floorEntry(50).getValue());
		System.out.println("floor 49 : " + map.floorEntry(49).getValue());
		// 反序map,还是在原来的数据上,只是迭代方式变化了
		System.out.print("descending : ");
		printSort(map.descendingMap());
		// keySet和navigableKeySet行为完全一样
		System.out.println();
		System.out.println("navigableKeySet : ");
		for (Integer key : map.navigableKeySet()) {
			System.out.print(key + " ");
		}
		System.out.println();
		System.out.println("keySet : ");
		for (Integer key : map.keySet()) {
			System.out.print(key + " ");
		}
		// 子Map
		System.out.print("\nsub map : ");
		printSort(map.subMap(30, 70));
		printSort(map.headMap(50));
		printSort(map.tailMap(50));
	}

	private static void printSort(SortedMap<Integer, String> map) {
		System.out.println();
		for (Entry<Integer, String> entry : map.entrySet()) {
			System.out.print(entry.getValue() + " ");
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值