Java Collections Factory Method Examples
- Details
- Written by Nam Ha Minh
- Last Updated on 11 April 2024   |   Print Email
- Collections.emptyList() example
- Collections.emptyMap() example
- Collections.emptySet() example
- Collections.singleton() example
- Collections.singletonList() example
- Collections.singletonMap() example
- Collections.nCopies() example
1. Returning Empty Collections
Empty collections can be useful in indicating no values return in methods that return collections of values, or in passing no-element collections to method that accepts collections of values.The Collections class provides the following methods that return an empty list, an empty set and empty map:- List<T> emptyList()
- Map<K,V> emptyMap()
- Set<T> emptySet()
Returning an empty list:
The following method is designed to return an empty list using the factory method:public List<String> getCountries() { if (/* the condition that returns a list having some elements */) { List<String> listCountries = Arrays.asList("USA", "UK"); return listCountries; } else { // the condition that returns an empty list return Collections.emptyList(); } }And here’s the calling code:
List<String> listCountries = getCountries(); if (listCountries == Collections.EMPTY_LIST) { System.out.println("Empty list: no country"); }The above reference comparison (using == operator) proves that the factory method returns a singleton instance of an empty list. You can also write like this for more readability:
if (listCountries.isEmpty()) { System.out.println("Empty list: no country"); }
Returning an empty map:
Similarly, the following method illustrates the scenario where an empty map should be returned:public Map<Integer, String> getErrors() { if (false) { // the condition that returns a map having some mappings Map<Integer, String> mapErrors = new HashMap<>(); mapErrors.put(500, "Internal Server Error"); return mapErrors; } else { // the condition that returns an empty map return Collections.emptyMap(); } }And the client code:
Map<Integer, String> mapErrors = getErrors(); if (mapErrors == Collections.EMPTY_MAP) { System.out.println("Empty map: No error found"); }
Returning an empty set:
Similarly, the following method illustrates the scenario in which we should return an empty set collection:public Set<Integer> getNumbers() { if (false) { // the condition that returns a set having some mappings Set<Integer> setNumbers = new HashSet<>(); setNumbers.add(123); setNumbers.add(987); return setNumbers; } else { // the condition that returns an empty set return Collections.emptySet(); } }and the calling code:
Set<Integer> setNumbers = getNumbers(); if (setNumbers == Collections.EMPTY_SET) { System.out.println("Emtpy set: no numbers"); }And the following example illustrates passing an empty collection to a method:
public void processList(List<String> list) { // processes the input list... }with the calling code:
processList(Collections.emptyList());
2. Creating Singleton Collections
The Collections class also provides convenient ways of creating collection objects containing only one element. These methods are:- Set<T> singleton(T o)
- List<T> singletonList(T o)
- Map<K,V> singletonMap(K key, V value)
Creating a singleton set:
Suppose this is the method that accepts a Set collection:public void processSet(Set<Integer> set) { // processes the input set... }then here how the client code looks like:
Set<Integer> setInput = Collections.singleton(new Integer(200)); processSet(setInput);
Creating a singleton list:
With the following method accepts a List collection:public void processList(List<String> list) { // processes the input list... }so the calling code:
List<String> listInput = Collections.singletonList("OK"); processList(listInput);
Creating a singleton map:
Given the following method that accepts a Map:public void processMap(Map<Integer, String> map) { // processes the input map... }Then the following code passes a singleton set to the method:
Map<Integer, String> mapInput = Collections.singletonMap(200, "OK"); processMap(mapInput);The singleton collection can be also useful when we need to remove all occurrences of a specified element from a collection, as shown in the example below:
List<String> listNames = new ArrayList<>( Arrays.asList("Joe", "Dan", "Carl", "Jack", "Tom", "Dan")); System.out.println("Before remove: " + listNames); listNames.removeAll(Collections.singletonList("Dan")); System.out.println("After remove: " + listNames);Output:
Before remove: [Joe, Dan, Carl, Jack, Tom, Dan] After remove: [Joe, Carl, Jack, Tom]
3. Creating Immutable Multiple-Copy List
Sometimes you will need an immutable List containing multiple copies of the same element. The following Collections’s method returns such a list:List<T> nCopies(int n, T o)
This method has two main uses, as explained in the following examples:Initializing a newly created list:
The following example creates an ArrayListinitially contain 1,000 null elements:List<String> list = new ArrayList<>(Collections.nCopies(1000, (String)null));
Growing an existing list:
The followng example enlarges an existing ArrayListto hold more 100 null elements:list.addAll(Collections.nCopies(100, (String)null));
References:
Related Collection Utility Classes Tutorials:
- Java Arrays Utility Class Examples for List view, Sorting and Searching
- Java Collections Utility Examples for Changing Order and Content of a List
- Java Collections Utility Examples for Searching in a Collection
- Java Collections Wrapper Methods Examples
Other Java Collections Tutorials:
- What is Java Collections Framework?
- Java Queue Tutorial
- Java List Tutorial
- Java Set Tutorial
- Java Map Tutorial
- Understand equals and hashCode
- Understand object ordering
- 18 Java Collections and Generics Best Practices
Comments