How to Get Synchronized Map from TreeMap in Java


In this example, we’ll learn how to get a synchronized Map from TreeMap using synchronizedMap method of Collections class in Java.

Source Code

package com.beginner.examples;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class GetSynchronizedMapFromJavaTreeMap {

	public static void main(String[] args) {
		//create TreeMap. 
		TreeMap treeMap = new TreeMap();
		
		/*
		  Java TreeMap is NOT synchronized. To get synchronized Map from
		  TreeMap use the method synchronizedMap() of Collections.
		 */
		Map map = Collections.synchronizedMap(treeMap);
		
		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:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments