Collections: empty and singleton collections avoid null returns

Returning an empty collection instead of null removes a whole class of NullPointerException. The factory instances allocate nothing.

Code
List<String> empty = Collections.emptyList();
Set<String> one = Collections.singleton("only");

System.out.println("empty list      = " + empty + ", isEmpty = " + empty.isEmpty());
System.out.println("singleton set   = " + one);
System.out.println("List.of() empty = " + List.of());

List<String> maybe = null;
System.out.println("null-safe size  = " + Objects.requireNonNullElse(maybe, List.<String>of()).size());
Output
empty list      = [], isEmpty = true
singleton set   = [only]
List.of() empty = []
null-safe size  = 0
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-30