Showing posts with label JAVA COLLECTIONS. Show all posts
Showing posts with label JAVA COLLECTIONS. Show all posts

Tuesday, July 21, 2015

Different Ways of Looping the Map in Java

INTRODUCTION

There are multiple ways to loop through a Map and display the Key and Value. They are:
  1. Using EntrySet
  2. Using KeySet
  3. Using Iterator
  4. Using Map Values

Below example will provide different ways of looping the Map Keys and its values.

EXAMPLE

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class LoopingMap {

 public static void main(String[] args) {

   Map<String, String> map = new HashMap<String, String>();
   map.put("1000", "Ranjith");
   map.put("2000", "Sekar");
   map.put("3000", "Bala");
   map.put("4000", "Kumar");
   map.put("5000", "Rekha");

   // Way 1: Using EntrySet
   System.out.println("===1. Using Map's EntrySet===");
   Set<Map.Entry<String, String>> entries = map.entrySet();
   for (Map.Entry<String, String> entry : entries) {
     System.out.println(entry.getKey() + " >> " + entry.getValue());
   }

   // Way 2: Using keySet
   System.out.println("\n===2. Using Map's KeySet===");
   Set<String> str = map.keySet();
   for (Object obj : str) {
     System.out.println(obj.toString() + " >> " + map.get(obj.toString()));
   }

   // Way 3: Using Iterator
   System.out.println("\n===3. Using Iterator===");
   Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
   while (iterator.hasNext()) {
     Entry<String, String> entry = iterator.next();
     System.out.println(entry.getKey() + " >> " + entry.getValue());
   }

   // Way 4: Using Map's Value (Iterators only Values in the Map)
   System.out.println("\n===4. Using Map's Values===");
   Collection<String> collection = map.values();
   Iterator<String> itr = collection.iterator();
   while (itr.hasNext()) {
     System.out.println(itr.next());
   }
 }
}

OUTPUT


===1. Using Map's EntrySet===
5000 >> Rekha
3000 >> Bala
4000 >> Kumar
1000 >> Ranjith
2000 >> Sekar

===2. Using Map's KeySet===
5000 >> Rekha
3000 >> Bala
4000 >> Kumar
1000 >> Ranjith
2000 >> Sekar

===3. Using Iterator===
5000 >> Rekha
3000 >> Bala
4000 >> Kumar
1000 >> Ranjith
2000 >> Sekar

===4. Using Map's Values===
Rekha
Bala
Kumar
Ranjith
Sekar