java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to create an empty collection object?

Sometimes you need to return an empty collection from your Java methods. Java java.util.Collections class have three different static instances for creating empty List, Set and Map. There are also methods when you want to create type-safe empty collections. Bellow it the code example.

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

public static void main(String args[])
  List list = Collections.EMPTY_LIST;
  Set set = Collections.EMPTY_SET;
  Map map = Collections.EMPTY_MAP;

  // For the type-safe example use the following methods.
  List<String> s = Collections.emptyList();
  Set<Long> l = Collections.emptySet();
  Map<Date> d = Collections.emptyMap();