Collections.singletonMap(E1, E2) in Java

Collections.singletonMap(E1, E2): This method is available in java.util.Collections class of Java.

Syntax:

<E1, E2> Map<E1, E2> java.util.Collections.singletonMap(E1 key, E2 value)

This method takes two arguments. This method returns an immutable map, mapping only the specified key to the specified value.

Note: The returned map is serializable.

Parameters: Two parameters are required for this method.

key: the sole key to be stored in the returned map.

value: the value to which the returned map maps key.

Returns: an immutable map containing only the specified key-value mapping.

Exceptions: NA

Approach

Java

import java.util.Collections;

public class CollectionssingletonMap {
    public static void main(String[] args) {

        String key = "Hello";
        int value = 2;
        System.out.println(Collections.singletonMap(key, value));

    }
}

Output:

{Hello=2}


No comments:

Post a Comment