Map遍历取值的四种方式

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/u013131716/article/details/101053968

Map代码中经常用的的内容,以下代码是对map遍历取值的方式进行总结
1.方式一 普遍使用 两次取值,先去key,再通过key获取value;
2.方式二 Iterator迭代;
3.方式三 推荐使用,尤其是大容量;
4.方式四 通过使用Map.values,但是不能遍历key。

实现代码

package com.test08.map;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.junit.Test;


/*
 * Map遍历取值的四种方式
 * 
 * */
	
public class MapGetValuesTest {
 
	@Test
	public void mapTest(){	
		Map<String, String> map = new HashMap<String, String>();
		
		map.put("01", "张三");
		map.put("02", "李四");
		map.put("03", "王五");		
		System.out.println(map);	
		
		//方式一  普遍使用  两次取值,先去key,再通过key获取value
		System.out.println("--------------------------通过Map.keySet()遍历key和value");		
		System.out.println(map);
		for(String key : map.keySet()){
			System.out.println("键:" + key +"  值:"+map.get(key));
		}		
				
		//方式二  Iterator迭代
		System.out.println("--------------------------通过Map.entrySet(),使用Iteration遍历key和value");
		Iterator<Entry<String, String>> it = map.entrySet().iterator();
		while(it.hasNext()){
			Entry<String, String> nextEntry = it.next();
			System.out.println("键:" + nextEntry.getKey() + "  值:" +nextEntry.getValue());;
		}
		
		//方式三  推荐使用,尤其是大容量
		System.out.println("--------------------------通过Map.entrySet()获取key和value");		
		System.out.println(map);
		for(Entry<String, String> mapz : map.entrySet()){
			System.out.println("键:" + mapz.getKey()+"  值:"+mapz.getValue());
		}
		
		//方式四 通过使用Map.values,但是不能遍历key
		System.out.println("--------------------------通过通过使用Map.values,但是不能遍历key");		
		System.out.println(map);
		for(String value : map.values()){
			System.out.println("值:"+value);
		}	
	}
}

猜你喜欢

转载自blog.csdn.net/u013131716/article/details/101053968