Map遍历的几种方法

基本上是如下3种或者4中方法

public class MapTest {

	private Map<String, String> map = null;

	@Before
	public void before() {
		map = new HashMap<String, String>();
		map.put("1", "a");
		map.put("2", "b");
		map.put("3", "c");
		map.put("4", "d");
	}

	/**
	 * 利用Map的内部接口Entry来实现 Entry(key-value)相当于Map中的一条记录 foreach
	 */
	@Test
	public void method1() {
		for (Map.Entry<String, String> entry : map.entrySet()) {
			System.out.println("the key is:" + entry.getKey()
					+ " the value is :" + entry.getValue());
		}
	}

	/**
	 * 如果只是需要获取里面的key,value,用这种方法就可以了
	 * 当然也可以获取key及get方法获取相应的value,即第4种方法
	 */
	@Test
	public void method2() {
		for (String key : map.keySet()) { // 因为key是不重复的,所以keySet返回值是一个set
			System.out.println("the key is: " + key);
		}

		for (String value : map.values()) { //因为value是可以重复的,所以values返回值是一个Collection
			System.out.println("the value is: " + value);
		}
	}

	/**
	 * 使用itreator迭代
	 */
	@Test
	public void method3() {
		Iterator<Entry<String, String>> it = map.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, String> entry = it.next();
			System.out.println("the key is:" + entry.getKey()
					+ " the value is :" + entry.getValue());
		}
	}
	
}

运行结果

the key is:3 the value is :c
the key is:2 the value is :b
the key is:1 the value is :a
the key is:4 the value is :d

为什么是这个顺序还不太清楚

参考 http://www.open-open.com/lib/view/open1378775803803.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值