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