Create singleton

ReturnMethodSummary
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;

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:


[Two, Three, One, Two, Three]
[Two, Three, Two, Three]

import java.util.Collections;

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:


[a]
[a]
{a=b}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.