在java中,所有map都实现了map接口,因此所有map都可以通过以下方式进行遍历: 本文主要介绍了在Java中遍历Map集合的五种方法。 示例代码中有详细介绍,对大家的学习和工作有参考价值,有需要的朋友可以学习如下。
方式通过Map.keySet使用iterator进行遍历
1. @Test
2 .公共语音测试hashmap1() {
3. Map map=new HashMap (;
4.map.put(001,' Java ';
5.map.put(002,'数据库');
6.map.put(003,' Vue ';
7. System.out.println(map )
8.
9 .在9.//map.keyset中使用迭代器遍历key,通过key获得相应的value值
10. Iterator iterator=map.keySet ().iterator );
11.while(iterator.Hasnext () ) ) ) ) )。
12. Integer key=iterator.next (;
13.stringvalue=map.get(key;
14.system.out.println (' key=' key ',value=' value );
15 ) }
16 ) }
结果:
1. {1=Java,2=数据库,3=Vue}
2. key=1,value=Java
3 .密钥=2,值=数据库
4. key=3,value=Vue
在方式Map.entrySet中使用迭代器进行遍历
1. @Test
2.public void测试hashmap2() {
3. Map map=new HashMap (;
4.map.put(001,' Java ';
5.map.put(002,'数据库');
6.map.put(003,' Vue ';
7. System.out.println(map )
8.
9 .在9.//map.entryset中使用迭代器遍历key和value; 注意Set entrySet () :返回由所有key-value对组成的Set集合
10.iterator entries=map.entryset ().iterator );
11.while(Entries.Hasnext () ) ) )。
12. Map.Entry entry=entries.next (;
13.system.out.println (入口)
14. }
15 ) }
结果:
1. {1=Java,2=数据库,3=Vue}
2. 1=Java
3. 2=数据库
4. 3=Vue
使用方式Map.keySet遍历
1. @Test
2.public void测试hashmap3() {
3. Map map=new HashMap (;
4.map.put(001,' Java ';
5.map.put(002,'数据库');
6.map.put(003,' Vue ';
7. System.out.println(map )
8.
9 .用9.//map.keyset遍历key,用key得到对应的value值
10.for (integer key : map.keyset ) ) }
11.system.out.println(key='key ',value='map.get ) key );
12. }
13. }
结果:
1. {1=Java,2=数据库,3=Vue}
2. key=1,value=Java
3 .密钥=2,值=数据库
4. key=3,value=Vue
通过方式四For-Each迭代条目,使用Map.entrySet进行遍历
1. @Test
2.public void测试hashmap4() {
3. Map map=new HashMap (;
4.map.put(001,' Java ';
5.map.put(002,'数据库');
6.map.put(003,' Vue ';
7. System.out.println(map )
8.
9 .使用9.//for-each迭代条目在Map.entrySet中遍历密钥和值
10.for (map.entry entry : map.entryset ) )
11.system.out.println (' key=' entry.getkey (),value=' entry.getValue ) );
12. }
13. }
结果
源代码事务处理: http://jy.iis7.com/supply7/
1. {1=Java,2=数据库,3=Vue}
2. key=1,value=Java
3 .密钥=2,值=数据库
4. key=3,value=Vue
使用方式lambda表达式forEach进行遍历
1. @Test
2 .公共语音测试混图5 () {
3. Map map=new HashMap (;
4.map.put(001,' Java ';
5.map.put(002,'数据库');
6.map.put(003,' Vue ';
7. System.out.println(map )
8.
9 .使用9.//lambda公式forEach进行遍历
10.map.foreach((k,v )-system.out.println ) ) key='k ',value=' v );
11. }
forEach源代码
1.defaultvoidforeach (biconsumersuperk? super v动作) {
2.objects.require nonnull (action );
3.for (map.entry entry :入口) ) }
4. K k;
5. V v;
6. try {
7. k=entry.getKey ();
8. v=entry.getValue (;
9.} catch (illegalstateexceptionise ) )
10.//thisusuallymeanstheentryisnolongerinthemap。
11.thrownewconcurrentmodificationexception (ise );
12. }
13.Action.accept(k,v );
14. }
15 ) }
从源代码可以看出,这个新功能在传统的迭代方法中增加了外壳,但使代码更简单。 (开发中推荐)
总结
建议使用entrySet而不是keySet方法遍历Map类集合KV。
keySet实际上遍历两次,第一次迁移到迭代器对象,第二次从hashMap中检索与key对应的值。 entrySet只是遍历了一次,将key和value都放入entry中会更有效率。
values ) )返回v值的集合,是list集合对象。 keySet ) )返回k值的集合,是Set集合对象。 entrySet ) )返回K-V值组合的集合。