Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

How to get an empty collection in Java

abhilash

This shot covers how to return an empty list, set, or map in Java.

Static constants of the Collections class

The Collections class contains the following static constants that give an empty collection. The collections attached to these constants have no type and are immutable in nature.

  1. Collections.EMPTY_LIST: returns an empty list.
  2. Collections.EMPTY_SET: returns an empty set.
  3. Collections.EMPTY_MAP: returns an empty map.

In the following code, we create empty collections with the help of the static constants of the Collections class. Here, you can observe that there is no type associated with the empty collection.

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Main {

    public static void main(String[] args){
        List emptyList = Collections.EMPTY_LIST;
        System.out.println("Size of empty list - " + emptyList.size());

        Set emptySet = Collections.EMPTY_SET;
        System.out.println("Size of empty set - " + emptySet.size());

        Map emptyMap = Collections.EMPTY_MAP;
        System.out.println("Size of empty map - " + emptyMap.size());
    }
}

Static methods in the Collections class

The Collections class contains the following static methods that return an empty collection. The collections returned to these constants are type-safe and are immutable in nature.

  1. Collections.emptyList(): method used to return an empty list.
  2. Collections.emptySet(): method used to return an empty set.
  3. Collections.emptyMap(): method used to return an empty map.

In the below code, we create empty collections with the help of the static methods of the Collections class. Here, you can observe that there is a type associated with the empty collection.

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Main {

    public static void main(String[] args){
        List<String> emptyList = Collections.emptyList();
        System.out.println("Size of empty list - " + emptyList.size());

        Set<String> emptySet = Collections.emptySet();
        System.out.println("Size of empty set - " + emptySet.size());

        Map<String, String> emptyMap = Collections.emptyMap();
        System.out.println("Size of empty map - " + emptyMap.size());
    }
}

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring