The example demonstrates how to get a synchronized Map from HashMap by synchronizedMap method in Java.
Source Code
package com.beginner.examples;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class GetSynchronizedMapFromJavaHashMap {
public static void main(String[] args) {
//create TreeMap
HashMap hashMap = new HashMap();
/*
Java TreeMap is NOT synchronized. To get synchronized Map from
TreeMap use the method synchronizedMap of Collections.
*/
Map map = Collections.synchronizedMap(hashMap);
map.put(1,"hello");
map.put(2,"world");
//Use Collection to output
Collection collection = map.values();
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next().toString());
}
}
}
Output:
helloworld
References
Imported packages in Java documentation: