Four ways for Java to traverse map objects

For the specific four ways to traverse map in Java, please see the following details.

This is the most common and, in most cases, the most desirable way to traverse. Used when both keys and values are required.

Method 2 traverses keys or values in the for each loop.

If you only need the keys or values in the map, you can traverse through keyset or values instead of entryset.

This method performs slightly better than entryset traversal (10% faster) and the code is cleaner.

Method 3 uses iterator to iterate

Use generics:

Do not use generics:

You can also apply the same method on keyset and values.

This approach seems redundant, but it has its advantages. First, in the old version of Java, this was the only way to traverse the map. Another advantage is that you can call the iterator when traversing Remove() to delete entries, the other two methods cannot. According to Javadoc, if you try to use this method in the for each traversal, the result is unpredictable.

In terms of performance, this method is similar to the performance of for each traversal (i.e. method 2).

Method 4. Traversal through key value finding (low efficiency)

As an alternative to method 1, this code looks cleaner; But it's actually quite slow and inefficient. Because fetching from key is a time-consuming operation (compared with method 1, this method is 20% ~ 200% slower in different map implementations). If you install findbugs, it will check and warn you about inefficient traversal. Therefore, try to avoid using findbugs.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>