Example of Collections.singleton in Java
May 31, 2013
On this page we will provide the use of java Collections.singleton, Collections.singletonList and Collections.singletonMap. They will return serialized and immutable java Set, List and Map respectively containing the given object. Find the example.
Collections.singleton
It returns a serialized and immutableSet
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); } }
package com.concretepage.util; public class User { private String name; public User(String name) { this.name = name; } public String getName() { return name; } }
Exception in thread "main" java.lang.UnsupportedOperationException at java.util.AbstractCollection.add(AbstractCollection.java:262) at com.concretepage.util.CollectionsSingleton.main(CollectionsSingleton.java:11)
Collections.singletonList
It returns a serialized and immutableList
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); } }
Collections.singletonMap
It returns a serialized and immutableMap
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); } }