1. Overview
Empty collections indicate that the collection does not have any values in it. All the empty collections are immutable which means once created they can be shared freely. Also this empty collections are singleton hence calling this method doesn’t result in creation of new object.
2. Content
When return type is Collection it is better to denote the result in terms of empty collection rather than null as nulls can create lot of problems like checking for null or throws NullPointerException, code gets bloated, etc.
Let us understand this with an example.
private List<String> getCustomers(List<Transaction> transactions) { if(transactions == null) return null; return transactions.stream() .map(t -> t.invoiceId()) .collect(Collectors.toList()); } List<String> invoiceIds = getCustomers(transactions); if(invoiceIds != null) { // iterate and log invoice id's. }
Checking nulls may seem trivial but it can create chaos. Think about the client who forgot to write a null check didn’t tested for that condition and that code is susceptible to fail. The code may work just fine as the method will usually return the List with values in it. But still there is danger looming around.
private List<String> getCustomers(List<Transaction> transactions) { if(transactions == null) return Collections.emptyList(); return transactions.stream() .map(t -> t.invoiceId()) .collect(Collectors.toList()); }
Below are empty static factories available in Collections class.
- List
- emptyList()
- Map
- emptyMap()
- emptyNavigableMap()
- emptySortedMap()
- Set
- emptyNavigableSet()
- emptySet()
- emptySortedSet()
List<Integer> emptyList = Collections.emptyList(); Set<Integer> emptySet = Collections.emptySet(); Set<Integer> emptySortedSet = Collections.emptySortedSet(); Set<Integer> emptyNavigableSet = Collections.emptyNavigableSet(); Map<String, Integer> emptyMap = Collections.emptyMap(); Map<String, Integer> emptyNavMap = Collections.emptyNavigableMap(); Map<String, Integer> emptySortedMap = Collections.emptySortedMap();
Conclusion, instead of returning null return empty collection.