Sometimes you need to return an empty collection from your Java methods. The java.util.Collections
utility class have three different static constants for creating empty List
, Set
and Map
.
Collections.EMPTY_LIST
Collections.EMPTY_SET
Collections.EMPTY_MAP
There are also methods when you want to create type-safe empty collections.
Collections.emptyList()
Collections.emptySet()
Collections.emptyMap()
Bellow it the code example.
package org.kodejava.util;
import java.util.*;
public class EmptyCollectionDemo {
public static void main(String[] args) {
List list = Collections.EMPTY_LIST;
System.out.println("list.size() = " + list.size());
Set set = Collections.EMPTY_SET;
System.out.println("set.size() = " + set.size());
Map map = Collections.EMPTY_MAP;
System.out.println("map.size() = " + map.size());
// For the type-safe example use the following methods.
List<String> strings = Collections.emptyList();
System.out.println("strings.size = " + strings.size());
Set<Long> longs = Collections.emptySet();
System.out.println("longs.size() = " + longs.size());
Map<String, Date> dates = Collections.emptyMap();
System.out.println("dates.size() = " + dates.size());
}
}
The output are:
list.size() = 0
set.size() = 0
map.size() = 0
strings.size = 0
longs.size() = 0
dates.size() = 0
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Map d = Collections.emptyMap(); //nice!
//I wonder if it compiles…
It does compile, and you can also create a type-safe
Map
object using theCollections.emptyMap()
as you can see in the code snippet above.Just browsing the net and came across your code! Very well structured and easy to understand. I might need a helping hand from you soon. Continue the good job and hopefully your work will be recognised by people.