4 ways to traverse a map in Java

Source: Internet
Author: User

How to traverse a map object in Java

How to iterate over a maps in Java

There are a number of ways to traverse a map in Java. Let's take a look at the most common methods and their pros and cons.

Since all maps in Java implement the map interface, the following methods apply to any map implementation (HASHMAP, TreeMap, Linkedhashmap, Hashtable, and so on)

Method one uses entries in the For-each loop to traverse

This is the most common and, in most cases, the most desirable way to traverse. Used when the key value is required.

[Java]View PlainCopy
    1. Map<integer, integer> map = new Hashmap<integer, integer> ();
    2. For (Map.entry<integer, integer> entry:map.entrySet ()) {
    3. System.out.println ("Key =" + entry.getkey () + ", Value =" + Entry.getvalue ());
    4. }



Note: The For-each loop is introduced in Java 5, so the method can only be applied to Java 5 or later. If you traverse an empty map object, the For-each loop will throw nullpointerexception, so you should always check for null references before traversing.

Method Two traverses the keys or values in the For-each loop.

If you only need the keys or values in the map, you can implement the traversal through keyset or values instead of using EntrySet.

[Java]View PlainCopy
  1. Map<integer, integer> map = new Hashmap<integer, integer> ();
  2. Traverse a key in a map
  3. For (Integer Key:map.keySet ()) {
  4. System.out.println ("key =" + key);
  5. }
  6. Traversing values in a map
  7. For (Integer value:map.values ()) {
  8. System.out.println ("value =" + value);
  9. }



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

Method three uses iterator traversal

Using generics:

[Java]View PlainCopy
    1. map<integer, integer> map =  new hashmap<integer, integer> ();   
    2.   
    3. iterator<map.entry<integer, integer>> entries = map.entryset () . iterator ();   
    4.   
    5. while  ( Entries.hasnext ())  {  
    6.   
    7.      Map.entry<integer, integer> entry = entries.next ();   
    8.   
    9.     system.out.println ( ", value = "  + entry.getvalue () );   
    10.   
    11. }&NBSP;&NBSP;



Do not use generics:

[Java]View PlainCopy
  1. Map map = new HashMap ();
  2. Iterator entries = Map.entryset (). Iterator ();
  3. while (Entries.hasnext ()) {
  4. Map.entry Entry = (map.entry) entries.next ();
  5. Integer key = (integer) entry.getkey ();
  6. Integer value = (integer) entry.getvalue ();
  7. System.out.println ("key =" + key + ", value =" + value ");
  8. }



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

This way of looking redundant has its advantages. First, this is the only way to traverse the map in the old version of Java. Another benefit is that you can delete the entries by calling Iterator.remove () over the duration, and the other two methods cannot. According to Javadoc, if you try to use this method in a 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 two).

Method Four, through the key to find the value traversal (low efficiency)

[Java]View PlainCopy
    1. Map<integer, integer> map = new Hashmap<integer, integer> ();
    2. For (Integer Key:map.keySet ()) {
    3. Integer value = Map.get (key);
    4. System.out.println ("key =" + key + ", value =" + value ");
    5. }



As an alternative to method one, the code looks cleaner, but in fact it is quite slow and inefficient. Because the value from the key is a time-consuming operation (compared to method one, the method is slower 20%~200% in different map implementations). If you install FindBugs, it will check and warn you about what is inefficient traversal. So try to avoid it.

Summarize

Use method Two if you only need keys or values. You must use method three if you are using a language version that is lower than Java 5, or if you plan to delete entries over time. Otherwise, use method one (the key value is all).

4 ways to traverse a map in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.