3:53 pm - Monday March 25, 8735

Java Collection Singleton Map examples

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

BACK

 

The singletonMap(K, V) method is used to get an immutable map, mapping only the specified key to the specified value.

Example Program


import java.util.*;

public class Map1 {
public static void main(String[] args) {
Map<Integer, String> m1 = new HashMap<Integer, String>();
m1.put(1, "sunday");
m1.put(2, "monday");
m1.put(3, "tuesday");
m1.put(4, "wednesday");
System.out.println("Before Singleton use");
System.out.println("Size of 'Map': " + m1.size());
System.out.println("Contents of the Map Elements");
System.out.print("\t" + m1);
System.out.println("\n");
System.out.println("After singleton used");
m1 = Collections.singletonMap(1, "monday");
System.out.println("Size of 'Map': " + m1.size());
System.out.println("Contents of the Map Elements");
System.out.println("\t" + m1);
}
}

 

Output:

Before Singleton use

Size of ‘Map’: 4

Contents of the Map Elements

{1=sunday, 2=monday, 3=tuesday, 4=wednesday}

After singleton used

Size of ‘Map’: 1

Contents of the Map Elements

{1=monday}

Explanation:

public static <K,V> Map<K,V> singletonMap(K key,V value)

The singletonMap(K, V) method is used to get an immutable map, mapping only the specified key to the specified value.

Parameters:

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.

Since:

1.3

BACK

 

Filed in: Z-A All Java Codes

Comments are closed.