This Java tutorial helps you understand how to use some common factory methods of the Collections utilty class in the Java Collections framework.

You know, the java.util.Collections utility class provides convenient ways of returning empty or pre-populated collections, which are implemented in the following methods:

These methods are categorized as “factory methods”. Let’s see how useful they are in the below examples.

 

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()
Each of these method returns a reference to a singleton instance of an inner class of Collections (corresponding to the constants EMPTY_LIST, EMPTY_MAP and EMPTY_SET of the Collections class). Because these instances are immutable, they can be safely shared, and invoking one of these factory methods does not result in object creation.

 

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");
}


The returned empty collection is safe, as it is immutable - nobody can assign it to other collection nor adding elements to it. So you got the ideas of returning an empty collection, right?

 

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)
The returned collections are immutable and contain only the specified object. These can be useful in passing single input value to a method that accepts a collection. Let’s see code examples with each method.

 

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:

 

Other Java Collections Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (CollectionsFactoriesExamples.java)CollectionsFactoriesExamples.java[Java Collections Code Example]3 kB

Add comment