xxxxxxxxxx
import java.util.HashMap;
import java.util.Map;
public class MapForEachExample {
public static void main(String[] args) {
// Creating a Map
Map<String, Integer> populationMap = new HashMap<>();
populationMap.put("New York", 8419600);
populationMap.put("Los Angeles", 3990456);
populationMap.put("Chicago", 2716000);
populationMap.put("Houston", 2328074);
populationMap.put("Phoenix", 1680992);
// Using forEach with Map.Entry
populationMap.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
// Alternative : for-each with Entry and entrySet()
for (Map.Entry<String, Integer> entry : populationMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
//Using forEach with method reference
System.out.println("\nUsing forEach with method reference:");
populationMap.forEach(MapForEachExample::printEntry);
// Alternative : normal for-each loop
Set<String> mapKeys = populationMap.keySet(); // contains all keys of the map
List<Integer> mapValues = populationMap.values(); // contains all values of the map
for (Integer key : mapKeys) {
System.out.println("Value: " + value);
}
for (Integer value : mapValues) {
System.out.println("Value: " + value);
}
}
private static void printEntry(String key, Integer value) {
System.out.println("Key: " + key + ", Value: " + value);
}
}
xxxxxxxxxx
Map<Integer,String> map=new HashMap<>();
map.put(1,"john");
map.put(2,"kale");
for(Map.Entry<Integer,String> x:map.entrySet()){
System.out.println(x.getKey());
System.out.println(x.getValue());
}
xxxxxxxxxx
MAP : is a (key-value format)
and keys are always unique,
and value can be duplicated.
- HashTable don't have null key, sychronized(thread-safe)
- LinkedHashMap can have null key, keeps order
- HasHMap can have null key, order is not guaranteed
- TreeMap doesn't have null key and keys are sorted
xxxxxxxxxx
// Map implementation using HashMap
Map<Key, Value> numbers = new HashMap<>();