Home » Java programming language

Java Collections synchronizedMap() Method with Example

Collections Class synchronizedMap() method: Here, we are going to learn about the synchronizedMap() method of Collections Class with its syntax and example.
Submitted by Preeti Jain, on February 07, 2020

Collections Class synchronizedMap() method

  • synchronizedMap() method is available in java.util package.
  • synchronizedMap() method is used to return the synchronized view of the given map (map).
  • synchronizedMap() method is a static method, it is accessible with the class name and if we try to access the method with the class object then also we will not get any error.
  • synchronizedMap() method does not throw an exception at the time of returning the synchronized map.

Syntax:

    public static Map synchronizedMap(Map map);

Parameter(s):

  • Map map – represents the map to be viewed in synchronized map.

Return value:

The return type of this method is Map, it returns synchronized view of the given map.

Example:

// Java program to demonstrate the example 
// of Map synchronizedMap() method of Collections

import java.util.*;

public class SynchronizedMapOfCollections {
    public static void main(String args[]) {
        // Instantiates a linked hashmap object
        Map < Integer, String > lhm = new LinkedHashMap < Integer, String > ();

        // By using put() method is to add
        // objects in a linked hashmap 
        lhm.put(10, "C");
        lhm.put(20, "C++");
        lhm.put(30, "JAVA");
        lhm.put(40, "PHP");
        lhm.put(50, "SFDC");

        // Display Linked HashMap
        System.out.println("linked hashmap: " + lhm);

        // By using synchronizedMap() method is to
        // represent the linked hashmap in synchronized view
        lhm = Collections.synchronizedMap(lhm);

        // Display Synchronized Linked HashMap
        System.out.println("Collections.synchronizedMap(lhm): " + lhm);
    }
}

Output

linked hashmap: {10=C, 20=C++, 30=JAVA, 40=PHP, 50=SFDC}
Collections.synchronizedMap(lhm): {10=C, 20=C++, 30=JAVA, 40=PHP, 50=SFDC}



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.