首页 > 编程知识 正文

遍历map的几种方式效率,hashmap循环遍历四种方式

时间:2023-05-03 09:33:15 阅读:30056 作者:2754

HashMap遍历(四种方法七种实现方式) HashMap遍历大致可分为四大类:

1、迭代器方式;

2、foreach方式;

3、lambda公式(JDK 1.8 );

4、流SAPI (JDK 1.8;

因为每种类型都有不同的实现方法,所以具体的遍历方法可以分为以下七种:

1、使用迭代器EntrySet方式;

2、使用迭代器密钥的方式;

3、使用foreach EntrySet的方式;

4、使用foreach KeySet方式;

5、使用lambda公式的方法;

6、使用流SAPI单线程的方式;

7、使用流SAPI多线程的方式;

接下来,我们来看看每个遍历方法的具体实现代码。

另一方面,反复器entrysetpublicclasshashmaptest { publicstaticvoidmain (string [ ] args (//hashmapmapinteger,stringmap=newHashaser ) map.put(2,' JDK '; map.put(3,' Spring '; map.put(4,' MyBatis '; IteratorMap.EntryInteger,String iterator=map.entrySet ().iterator ); while(iterator.Hasnext () ) { Map.EntryInteger,String entry=iterator.next; 系统. out.print (entry.getkey ) ); system.out.print (输入. getvalue (); }}二、迭代器keysetpublicclasshashmaptest { publicstaticvoidmain (string [ ] args (//hashmapmapinteger,stringmap=neest map.put(2,' JDK '; map.put(3,' Spring '; map.put(4,' MyBatis '; //iteratorintegeriterator=map.keyset ().iterator ); wile(iterator.Hasnext () ) { Integer key=iterator.next; 系统. out.print (key; system.out.print(map.get ) key ); }}三、foreachentrysetpublicclasshashmaptest { publicstaticvoidmain (字符串[ ] args (//hashmapmapinteger,字符串)创建并分配map.put(2,' JDK '; map.put(3,' Spring '; map.put(4,' MyBatis '; //for(map.entryinteger,String entry : map.entrySet () (system.out.print ) entry.getkey ) ); system.out.print (输入. getvalue (); (四. foreachkeysetpublicclasshashmaptest ) publicstaticvoidmain (string [ ] args ) HashMap MapInteger,stringmapinteger,ststap map.put(2,' JDK '; map.put(3,' Spring '; map.put(4,' MyBatis '; //for遍历(integerkey:map.keyset ) ) system.out.print (key ); system.out.print(map.get ) key ); }}五、lambdapublicclasshashmaptest { publicstaticvoidmain (string [ ] args (//hashmapmapinteger,stringmap=new ) map.put(2,' JDK '; map.put(3,' Spring '; map.put(4,' MyBatis '; //map.foreach((key,value )-) system.out.print ) key ); 系统. out.print (value; ); (六、创建流SAPI单线程公共映射publicclasshashmaptest publicstaticvoidmain (string [ ] args ) HashMap MapInteger,stringmap=map.put(2,' JDK '; map.put(3,' Spring '; map.put(4,' MyBatis '; //map.entryset(.stream ).foreach ) ) (entry )-{system.out.print ) entry.getkey ) }; system.out.print (输入. getvalue (); ); (七、StreamsAPI多线程publicclasshashmaptest publicstaticvoidmain (string [ ] args ) HashMap MapInteger,stringmap=(创建map.put(2,' JDK '; map.put(3,' Spring '; map.put(4,' MyBatis '; //map.entryset(.parallelstream ).foreach ) (entry )-{system.out.print ) entry.getkey; system.out.print (输入. getvalue (); ); }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。