skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Monday, October 15, 2012

Print contents of a map of type String ArrayList

Posted by Raju Gupta at 12:00 PM – 0 comments
 

The code snippet allows user to iterate through the contents of a map with String , ArrayList entryset

The solution provides an easy way to iterate through the map. The solution can be used in phonebook examples, where many contact numbers can be stored against a single user.


import java.io.IOException;
import java.util.*;

public class NewClass1 {
 public static void main(String[] args) throws IOException {
  Map<String, List> numMap = new HashMap<String, List>();
  numMap.put("Key1", new ArrayList(Arrays.asList("K1V1", "K1V2", "K1V3")));
  numMap.put("Key2", new ArrayList(Arrays.asList("K2V1", "K2V2", "K2V3")));
  numMap.put("Key3", new ArrayList(Arrays.asList("K3V3", "K3V2", "K3V3")));
  numMap.put("Key4", new ArrayList(Arrays.asList("K4V1", "K4V2", "K4V3")));

  Iterator itr = numMap.entrySet().iterator();

  while (itr.hasNext()) {

   Map.Entry keyValue = (Map.Entry) itr.next();

   System.out.println("Key: " + keyValue.getKey());

   /* Iterate through the list of each key */

   List value = (List) keyValue.getValue();

   for (int i = 0; i < value.size(); i++) {

    if (value != null) {

     if (value.get(i) != null) {

      System.out.println("Value: " + value.get(i));

     }

    }

   }

  }

 }
}

Labels: ArrayList Examples , Java Map Example

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger