Sep 14, 2018

Java Collections.singleton() Example

Java Collections.singleton() Example

public static <T> Set<T> singleton(T o)
Returns an immutable set containing only the specified object. The returned set is serializable.
Parameters:
o - the sole object to be stored in the returned set.
Returns:
an immutable set containing only the specified object.
   // create an array of string objs
   String init[] = { "i88", "ca", "i88", "ca" };
   // create two lists
   List list1 = new ArrayList(Arrays.asList(init));
   List list2 = new ArrayList(Arrays.asList(init));

   // remove from list1
   list1.remove("i88");
   System.out.println("List1 value: "+list1);

   // remove from list2 using singleton
   list2.removeAll(Collections.singleton("i88"));          
   System.out.println("The SingletonList is :"+list2);
   }
/* output
List1 value: [ca, i88, ca]
The SingletonList is :[ca, ca]
*/