0
Sponsored Links


Ad by Google
One of the interesting question as a developer you must have to know the ways of traversing a HashMap in java. Most of the time interviewer also asked you to list down the ways of traversing a HashMap in java. Below we have listed four different ways of traversing a HashMap in java.

  1. For Each
  2. Iterator
  3. EntrySet
  4. EntrySet with iterator

TraversingMap.java

package com.collection;

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

public class TraversingMap {

 Map<String, String> pizza = new HashMap<String, String>();

 public TraversingMap() {

  pizza.put("Large", "200");
  pizza.put("Medium", "175");
  pizza.put("Small", "150");
 }
 
 // 1st way to traverse a HashMap
 public void forEach() {
  for (String key : pizza.keySet()) {
   System.out.println("Key= " + key + " Value= " + pizza.get(key));
  }
 }

 // 2nd way to traverse a HashMap
 public void iterator() {
  Iterator<String> keySet = pizza.keySet().iterator();
  while (keySet.hasNext()) {
   String string = (String) keySet.next();
   System.out.println("Key= " + string + " Value= "
     + pizza.get(string));

  }

 }

 // 3rd way to traverse a HashMap
 public void entrySet() {
  Set<Map.Entry<String, String>> entrySets = pizza.entrySet();
  for (Entry<?, ?> entry : entrySets) {
   System.out.println("Key= " + entry.getKey() + " Value= "
     + entry.getValue());
  }
 }

 // 4th way to traverse a HashMap
 public void entrySetIte() {
  Iterator<Map.Entry<String, String>> entrySets = pizza.entrySet()
    .iterator();
  while (entrySets.hasNext()) {
   Map.Entry<java.lang.String, java.lang.String> entry = (Map.Entry<java.lang.String, java.lang.String>) entrySets
     .next();
   System.out.println("Key= " + entry.getKey() + " Value= "
     + entry.getValue());

  }
 }

 public static void main(String[] args) {

  new TraversingMap().forEach();
  new TraversingMap().iterator();
  new TraversingMap().entrySet();
  new TraversingMap().entrySetIte();
 }
}

That's it.

Few very popular java interview questions:
Which Collection is better to store 10 millions of record between ArrayList and LinkedList.
What are the Key differences between Comparable and Comparator.
Serializable Vs Externalizable.
Java program to find missing numbers
Why String is Immutable in java

Sponsored Links

0 comments:

Post a Comment