Abstract: All maps in Java implement the Map interface, so all maps can be traversed in the following way.

All maps in Java implement the Map interface, so all maps can be traversed in the following way. This article mainly introduces five ways to traverse the Map set in Java. It is very detailed through the example code. It has certain reference learning value for everyone’s study or work.

Method 1: Iterator iterator through map. keySet

Results:

Method 2 Use map. entrySet to iterate using iterator

Results:

Method 3 Traversal through map. keySet

Results:

Method 4 Iterate through entries through for-each, using map. entrySet

Method 5 uses the lambda expression forEach to traverse

The forEach source

From the source code, this new feature adds a shell to the traditional iterative approach, but makes the code much simpler. (Recommended in development)

conclusion

It is recommended to use entrySet to traverse the Map class collection KV (the fourth method in this article) rather than keySet.

The keySet is iterated twice, first to Iterator, and then to fetch the value of the key from the hashMap. EntrySet is more efficient by simply iterating once and putting both the key and the value into the entry.

Values () returns a set of V values, which is a list collection object; KeySet () returns a Set of K values, which is a Set object; EntrySet () returns a collection of combinations of k-V values.

For JDK8, the map.foreach method (the fifth method in this article) is recommended.

In this paper, the author: sail to the sea The original link: zhangxy.blog.csdn.net/article/det…

Click to follow, the first time to learn about Huawei cloud fresh technology ~