map遍历的几种方式
1、通过map.entrySet( )遍历:
Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i < 4; i++) { String s = "数字" + i; map.put("zhi-" + i, s); } Set<Entry<String, String>> s = map.entrySet(); int size = s.size(); for(Map.Entry<String,String> entry:map.entrySet()) { String value =entry.getValue(); String key = entry.getKey(); System.out.println("key:"+key+",value:"+value); }
输出结果为:
key:zhi-0,value:数字0 key:zhi-1,value:数字1 key:zhi-2,value:数字2 key:zhi-3,value:数字3
2、通过map.keySet()及map.value()遍历:
Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i < 4; i++) { String s = "数字" + i; map.put("zhi-" + i, s); } for (String key : map.keySet()) { System.out.println(key); } for(String value:map.values()) { System.out.println(value); }
输出结果为:
zhi-0 zhi-1 zhi-2 zhi-3 数字0 数字1 数字2 数字3
3、使用 Iterator遍历:
Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i < 4; i++) { String s = "数字" + i; map.put("zhi-" + i, s); } Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> data = entries.next(); System.out.println("key:" + data.getKey() + ",value:" + data.getValue()); }
输出结果为:
key:zhi-0,value:数字0 key:zhi-1,value:数字1 key:zhi-2,value:数字2 key:zhi-3,value:数字3
4、通过map.get(key)遍历:
Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i < 4; i++) { String s = "数字" + i; map.put("zhi-" + i, s); } for(String key:map.keySet()) { String value = map.get(key); System.out.println(key+" "+value); }
输出结果为:
zhi-0 数字0 zhi-1 数字1 zhi-2 数字2 zhi-3 数字3
推荐学习:java视频教程(公益免费)
以上就是map遍历的几种方式是什么的详细内容,更多请关注易知道|edz.cc其它相关文章!