Collection singleton

In this chapter you will learn:

  1. Create singleton set, map or list
  2. How to create singleton collection from array

Create singleton Collection

  • static<T> Set<T> singleton(T o) Returns an immutable set containing only the specified object.
  • static<T> List<T> singletonList(T o) Returns an immutable list containing only the specified object.
  • static<K,V> Map<K,V> singletonMap(K key, V value) Returns an immutable map, mapping only the specified key to the specified value.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/*  j  av  a2 s.  co  m*/
public class MainClass {
  public static void main(String args[]) {
    String init[] = { "One", "Two", "Three", "One", "Two", "Three" };
    List list1 = new ArrayList(Arrays.asList(init));
    List list2 = new ArrayList(Arrays.asList(init));
    list1.remove("One");
    System.out.println(list1);
    list2.removeAll(Collections.singleton("One"));
    System.out.println(list2);
  }
}

The output:

Singleton from array

import java.util.Collections;
//from   j av a2  s  .  c  om
public class Main {
  public static void main(String[] a){
     System.out.println(Collections.singletonList("a")); 
     System.out.println(Collections.singleton("a"));
     System.out.println(Collections.singletonMap("a","b"));
  
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. Get the max and min value from a Collection
Home » Java Tutorial » Collections
Iterator
ListIterator
Collection unmodifiable
Collection synchronized
Collection singleton
Collection max/min value
Empty Collections
Comparator
Comparable
Enumeration
EnumSet
EnumMap Class
PriorityQueue