Iterate /loop HashMap collection having string objects (Java8/ example)

1. What is HashMap collection in java?

  1. HashMap is Hash table based implementation of the Map interface.
  2. HashMap provides constant-time performance for the basic operations like get & put.
  3. HashMap is not thread safe.
    • HashMap must synchronized externally, If multiple threads access the hashmap concurrently.
  4. We will iterate or loop through HashMap collection using following methods:
    1. Iterate HashMap<String, String> using forEach method of java 8
    2. Iterate HashMap<String, String> using entrySet Iterator.

2. Class hierarchy of HashMap collection:

Fig 1: Class hierarchy of HashMap collection

3. Iterate /loop HashMap collection having string objects (Java8/example)

package org.learn.collection.map.hmap;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
 
public class DemoIterationHashMap {
 
    public static void main(String[] args) {
        Map<String, String> mapSportsPersonality = new HashMap<>();
        mapSportsPersonality.put("Tennis", "Federer");
        mapSportsPersonality.put("Cricket", "Bradman");
        mapSportsPersonality.put("Basketball", "Jordan");
        mapSportsPersonality.put("Golf", "Woods");
        mapSportsPersonality.put("Boxer", "Ali");
 
        System.out.println("Demo: Iterate HashMap collection in java ");
        demoIterateMethod(mapSportsPersonality);
    }
 
    private static void demoIterateMethod(Map<String, String> mapSportsPersonality) {
 
        System.out.println("1. Iterate HashMap using forEach method:");
        // Output using Java 8
        mapSportsPersonality.forEach((key, value) -> {
            System.out.println("Game:" + key + ", Player:" + value);
        });
 
        System.out.println("\n2. Iterate HashMap collection using entrySet iterator:");
        // Output use Iterator:
        Set<Entry<String, String>> entrySet = mapSportsPersonality.entrySet();
        Iterator<Entry<String, String>> iterator = entrySet.iterator();
        while(iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            System.out.println("Game:" + entry.getKey() + ", Player:" + entry.getValue());
        }
    }
}

4. Output – Iterate /loop HashMap collection having string objects in Java8

Demo: Iterate HashMap collection in java
1. Iterate HashMap using forEach method:
Game:Tennis, Player:Federer
Game:Cricket, Player:Bradman
Game:Golf, Player:Woods
Game:Basketball, Player:Jordan
Game:Boxer, Player:Ali
 
2. Iterate HashMap collection using entrySet iterator:
Game:Tennis, Player:Federer
Game:Cricket, Player:Bradman
Game:Golf, Player:Woods
Game:Basketball, Player:Jordan
Game:Boxer, Player:Ali