Map循环遍历的五种方法
先使用Map方法定义数据
Map map = new HashMap(); map.put(0,"张三"); map.put(1,"李四"); map.put(2,"王五");
1.通过key的set集合进行遍历,然后通过key来取map的value
Set set = map.keySet(); for (Object o : set) { System.out.println(o+" "+map.get(o)); }
运行结果:
2.将key的set集合以迭代器的方式遍历出来,然后通过key来取map的value。
Set set = map.keySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()){ Object next = iterator.next(); System.out.println("key为:"+next+",value为:"+map.get(next)); }
运行结果:
3.将Map的键值对以迭代器的方式遍历出来,然后通过.getKey()与.getValue()方法取k、v的值。
Set<Map.Entry<Object, Object>> entries = map.entrySet(); Iterator<Map.Entry<Object, Object>> iterator1 = entries.iterator(); while (iterator1.hasNext()){ Map.Entry<Object, Object> next = iterator1.next(); System.out.println("key为:"+next.getKey()+",value为:"+next.getValue()); }
运行结果:
4.此方法直接取出map的value并放在collection中,然后将v循环遍历
Collection<Object> values = map.values(); for (Object value : values) { System.out.println("value为:"+value); }
运行结果:
5.取得所有键值对来通过foreach循环,遍历出所有k、v,理论上推荐这种方法,尤其是容量较大的时候。
Set<Map.Entry<Object, Object>> entries = map.entrySet(); for (Map.Entry<Object, Object> entry : entries) { System.out.println("key为:"+entry.getKey()+",value为:"+entry.getValue()); }
运行结果:
标签:Map,set,java,map,value,next,五中,key From: https://www.cnblogs.com/leichenyu/p/17858930.html