Home » Java programming language

Java Collections singletonMap() Method with Example

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

Collections Class singletonMap() method

  • singletonMap() method is available in java.util package.
  • singletonMap() method is used to return an immutable map (i.e. immutable map is a map that contains the given key & value only & mapping would be based on the given key to the given value.
  • singletonMap() method is a static method, so it is accessible with the class name and if we try to access the method with the class object then we will not get an error.
  • singletonMap() method does not throw an exception at the time of returning an immutable map.

Syntax:

    public static Map singletonMap(Type key_ele, Type val_ele);

Parameter(s):

  • Type key_ele – represents the key to be saved in the returned map.
  • Type val_ele – represents the value(val) associated with the key_ele.

Return value:

The return type of this method is Map, it returns an immutable map that contains the given key-value pairs only of the map.

Example:

// Java program is to demonstrate the example of
// singletonMap(Type key_ele, Type val_ele)
// method of Collections

import java.util.*;

public class SingletonMapOfCollections {
    public static void main(String args[]) {
        // Instatiates a hash map object
        Map < Integer, String > map = new HashMap < Integer, String > ();

        // By using put() method is to add
        // objects in a hash map
        map.put(10, "C");
        map.put(20, "C++");
        map.put(30, "JAVA");
        map.put(40, "C");
        map.put(50, "C++");

        // Display Map
        System.out.println("Map: " + map);

        // By using singletonMap() method is to
        // list the given key-value pair only
        map = Collections.singletonMap(30, "JAVA");

        // Display SingletonMap
        System.out.println("Collections.singletonMap(30,JAVA): " + map);
    }
}

Output

Map: {50=C++, 20=C++, 40=C, 10=C, 30=JAVA}
Collections.singletonMap(30,JAVA): {30=JAVA}


Comments and Discussions!

Load comments ↻





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