Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java singleton List

farenda 2015-08-12 0

Problem:

How to create Java singleton List is the easiest way? Java Collections Framework has a couple of handy methods to create singleton List, singleton Set, and singleton Map. See the example.

Solution:

In java.util.Collections there are the following helper methods:

  • <T> Set<T> singleton(T o): creates an immutable Set with given element
  • <T> List<T> singletonList(T o): creates an immutable List with given element
  • <K,V> Map<K,V> singletonMap(K key, V value): creates an immutable Map with only the given pair.

In the following example Java program you can see that the created collection is really immutable and trying to do any modification results in UnsupportedOperationException:

package com.farenda.java;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class CollectionsSingleton {

    public static void main(String[] args) {
        showImmutability();

        System.out.println();

        showUseCase();
    }

    private static void showImmutability() {
        List<Integer> singleton = Collections.singletonList(42);

        System.out.println("singleton List: " + singleton);

        try {
            singleton.add(3);
        } catch (UnsupportedOperationException e) {
            System.out.println("While adding: " + e);
        }

        try {
            singleton.remove(0);
        } catch (UnsupportedOperationException e) {
            System.out.println("While removing: " + e);
        }

        try {
            singleton.set(0, 3);
        } catch (UnsupportedOperationException e) {
            System.out.println("While setting: " + e);
        }
    }

    private static void showUseCase() {
        List<String> scores = new LinkedList<>(Arrays.asList("1", "2", "3", "1", "4"));
        System.out.println("Scores: " + scores);
        scores.remove("1");
        System.out.println("After scores.remove(1): " + scores);

        scores = new LinkedList<>(Arrays.asList("1", "2", "3", "1", "4"));
        System.out.println("Scores: " + scores);
        scores.removeAll(Collections.singleton("1"));
        System.out.println("After scores.removeAll(singleton(1)): " + scores);
    }
}

In the method showUseCase() you can see how Collections.singleton(T o) is used to create an one-element collection to remove all occurrences of an object in the List.

Note that in the example we have to wrap List created by Arrays.asList() into another List, because the former one doesn’t support remove() operation, so we wouldn’t be able to remove anything.

And here’s the result of running the Java program:

singleton List: [42]
While adding: java.lang.UnsupportedOperationException
While removing: java.lang.UnsupportedOperationException
While setting: java.lang.UnsupportedOperationException

Scores: [1, 2, 3, 1, 4]
After scores.remove(1): [2, 3, 1, 4]
Scores: [1, 2, 3, 1, 4]
After scores.removeAll(singleton(1)): [2, 3, 4]

As an alternative to singleton methods from java.util.Collections you can use unmodifiable series of methods from java.util.Collections or ImmutableSet, ImmutableList, and ImmutableMap from great Guava library.

Share with the World!
Categories Java Tags java-collections
Previous: Java randomly shuffle
Next: Java sort List

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2022

sponsored