Example of Collections.singleton in Java

By Arvind Rai, November 12, 2023
On this page, we will learn using Java Collections.singleton, Collections.singletonList and Collections.singletonMap. They return serialized and immutable Java Set, List and Map respectively containing the specified object.
Find the example.

1. Collections.singleton

Collections.singleton returns a serialized and immutable Set containing given object.
CollectionsSingleton.java
package com.concretepage.util;
import java.util.Collections;
import java.util.Set;
public class CollectionsSingleton {
     public static void main(String[] args) {
         User user1 = new User("Mahesh");
         Set<User> set= Collections.singleton(user1);

         User user2 = new User("Ramesh");
         //will throw error
         set.add(user2);
     }
 }
User.java
package com.concretepage.util;
public class User {
   private String name;
   public User(String name) {
       this.name = name;
   }
   public String getName() {
       return name;
   }
}
Output
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractCollection.add(AbstractCollection.java:262)
	at com.concretepage.util.CollectionsSingleton.main(CollectionsSingleton.java:11) 

2. Collections.singletonList

Collections.singletonList returns a serialized and immutable List containing given object.
CollectionsSingletonList.java
package com.concretepage.util;
import java.util.Collections;
import java.util.List;
public class CollectionsSingletonList {
     public static void main(String[] args) {
         User user1 = new User("Mahesh");
         List<User> list= Collections.singletonList(user1);
         System.out.println(list.get(0).getName());

         User user2 = new User("Ramesh");
         //will throw error
         list.add(user2);
     }
 }

3. Collections.singletonMap

Collections.singletonMap returns a serialized and immutable Map containing given key and value.
CollectionsSingletonMap.java
package com.concretepage.util;
import java.util.Collections;
import java.util.Map;
public class CollectionsSingletonMap {
     public static void main(String[] args) {
         User user1 = new User("Mahesh");
         Map<Integer, User> map= Collections.singletonMap(1, user1);
         System.out.println(map.get(1).getName());

         User user2 = new User("Ramesh");
         //will throw error         
         map.put(2, user2);
     }
 }
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us