java之Map集合遍歷幾種方法
阿新 • • 發佈:2018-11-06
package cn.com.javatest.collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * java之Map集合遍歷幾種方法 * * @author: Rodge * @time: 2018年10月4日 下午3:03:03 * @version: V1.0.0 */ public class MapTest { public static void main(String[] args) { Map<String, Object> map = new HashMap<>(); map.put("1", "java"); map.put("2", "C"); map.put("3", "C++"); map.put("4", "C#"); map.put("5", "PHP"); /* * 第一種:增強for迴圈map.keySet() */ for (String s : map.keySet()) { System.out.println("key:" + s + " value:" + map.get(s)); } /* * 第二種:增強for迴圈map.entrySet() */ for (Map.Entry<String, Object> entry : map.entrySet()) { System.out.println("key:" + entry.getKey() + " value:" + entry.getValue()); } /* * 第三種:迭代器遍歷 */ Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> entry = it.next(); System.out.println("key:" + entry.getKey() + " value:" + entry.getValue()); } /* * 第四種:java8 Lambda表示式 */ map.forEach((k, v) -> { System.out.println("key:" + k + " value:" + v); }); } }