關於Map集合的遍歷總結

weixin_30924079發表於2020-04-04

轉:http://www.cnblogs.com/lsgspace/p/4666020.html

 

以下是遍歷Map集合的幾種方式:

public static void main(String[] args)
{
	Map<String, String> map = new HashMap<String, String>();
	map.put("1", "張三");
	map.put("2", "李四");
	map.put("3", "王五");
	
	//呼叫
}

  

1、通過Map.keySet遍歷key和value

private static void findKey(Map<String, String> map)
{
	System.out.println("findKey");

	for (String key : map.keySet())
	{
		System.out.println("key = " + key);
		System.out.println("value = " + map.get(key));
	}
}

2、通過Map.values遍歷value

private static void findValue(Map<String, String> map)
{
	System.out.println("findValue");

	for (String value : map.values())
	{
		System.out.println("value = " + value);
	}
}

3、通過Map.entrySet和迭代器遍歷Map

private static void findIterator(Map<String, String> map)
{
	System.out.println("findIterator");

	Iterator<Map.Entry<String, String>> carIterator = map.entrySet()
			.iterator();

	while (carIterator.hasNext())
	{
		Map.Entry<String, String> entry = carIterator.next();
		System.out.println("key = " + entry.getKey());
		System.out.println("value = " + entry.getValue());
	}
}

4、Map.entrySet加for in 迴圈(推薦)

private static void findEntrySet(Map<String, String> map)
{
	System.out.println("findEntrySet");

	for (Entry<String, String> entry : map.entrySet())
	{
		System.out.println("key = " + entry.getKey());
		System.out.println("value = " + entry.getValue());
	}
}

 

轉載於:https://www.cnblogs.com/fengzhentian/p/4666936.html

相關文章