java map的遍历的方法
map的遍历在java编程中经常使用,因此整理一下相关的资料,map的四种遍历方法:
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class MapTest { private Map<String, String> map; public MapTest() { map = new HashMap<String, String>(); map.put("1", "aa"); map.put("2", "bb"); map.put("3", "cc"); } // 第一种方法(传统方法) public void mapOne() { Set<String> set = map.keySet(); Iterator<String> it = set.iterator(); while (it.hasNext()) { String key = (String) it.next(); String value = (String) map.get(key); System.out.println(key + "=" + value); } } // 第二种方法(传统方法) public void mapTwo() { Set set = map.entrySet(); Iterator it = set.iterator(); while (it.hasNext()) { Entry entry = (Entry) it.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); System.out.println(key + "=" + value); } } // 第三种方法(增强for循环方法) public void mapThree() { for (Object obj : map.keySet()) { String key = (String) obj; String value = (String) map.get(key); System.out.println(key + "=" + value); } } // 第四种方法(增强for循环方法) public void mapFour() { for (Object obj : map.entrySet()) { Entry entry = (Entry) obj; String key = (String) entry.getKey(); String value = (String) entry.getValue(); System.out.println(key + "=" + value); } } public static void main(String[] args) { MapTest mapTest = new MapTest(); System.out.println("=====first====="); mapTest.mapOne(); System.out.println("=====second====="); mapTest.mapTwo(); System.out.println("=====three====="); mapTest.mapThree(); System.out.println("=====four====="); mapTest.mapFour(); } }