Java5种遍历HashMap数据的写法
本文介绍了最好的Java5种遍历HashMap数据的写法,分享给大家,也给自己留一个笔记,具体如下:
通过EntrySet的迭代器遍历
Iterator < Entry < Integer, String >> iterator = coursesMap.entrySet().iterator();while (iterator.hasNext()) { Entry < Integer, String > entry = iterator.next(); System.out.print(entry.getKey() + '. '); System.out.println(entry.getValue());}
输出结果如下:
zzw:how_iterate_hashmap_in_java zzw$ java IterateHashMapExample 1TIOBE Index for March 2020:1. Java2. C3. Python4. C++5. C#6. Visual Basic .NET7. JavaScript8. PHP9. SQL10. GO
通过KeySet的迭代器遍历
Iterator < Integer > iterator = coursesMap.keySet().iterator();while (iterator.hasNext()) { Integer key = iterator.next(); System.out.print(key + '. '); System.out.println(coursesMap.get(key));}
输出结果如下:
zzw:how_iterate_hashmap_in_java zzw$ java IterateHashMapExample 2TIOBE Index for March 2020:1. Java2. C3. Python4. C++5. C#6. Visual Basic .NET7. JavaScript8. PHP9. SQL10. GO
通过ForEach循环遍历
for (Map.Entry < Integer, String > entry: coursesMap.entrySet()) { System.out.print(entry.getKey() + '. '); System.out.println(entry.getValue());}
输出结果如下:
zzw:how_iterate_hashmap_in_java zzw$ java IterateHashMapExample 3TIOBE Index for March 2020:1. Java2. C3. Python4. C++5. C#6. Visual Basic .NET7. JavaScript8. PHP9. SQL10. GO
通过Lambda表达式遍历
coursesMap.forEach((key, value) -> { System.out.print(key + '. '); System.out.println(value);});
输出结果如下:
zzw:how_iterate_hashmap_in_java zzw$ java IterateHashMapExample 4TIOBE Index for March 2020:1. Java2. C3. Python4. C++5. C#6. Visual Basic .NET7. JavaScript8. PHP9. SQL10. GO
通过Stream API遍历
coursesMap.entrySet().stream().forEach((entry) -> { System.out.print(entry.getKey() + '. '); System.out.println(entry.getValue());});
输出结果如下:
zzw:how_iterate_hashmap_in_java zzw$ java IterateHashMapExample 5TIOBE Index for March 2020:1. Java2. C3. Python4. C++5. C#6. Visual Basic .NET7. JavaScript8. PHP9. SQL10. GO
完整示例代码在这里
到此这篇关于Java5种遍历HashMap数据的写法的文章就介绍到这了,更多相关Java遍历HashMap内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!
相关文章: