3 static factory families of Collections class

1. Introduction

java.util.Collections class is static utility class which contains polymorphic algorithms, static factories and wrapper methods. It also contains several other interesting methods. All the methods of Collections class operate on collections and all methods are static.

2. Content

In this article, I will talk about 3 types of factory method families provided in Collections class. Below are 3 families of static factories:

  • Static factory for empty collections
  • Static factory for single element
  • Static factory for n copies of specified object

3. Static factory for empty collections

Empty Collection is explained here.

4. Static factory for single element

  • List
    1. singletonList(T o) // returns List<T>
  • Map
    1. singletonMap(K key, V value) // returns Map<K, V>
  • Set
    1. singleton(T o) // returns Set<T>
List<Integer> singleElementList = 
		Collections.singletonList(Integer.valueOf(42));
 
Set<Integer> singleElementSet = 
		Collections.singleton(Integer.valueOf(42));
 
Map<String, Integer> singleEntryMap = 
		Collections.singletonMap("Forty Two", Integer.valueOf(42));

Singleton factory methods provides a way to create a Collection of a single element. This returned collections are immutable which contains only one element.

Specifically they are helpful where a method would accept a collection with single element as a parameter and/or a method which returns collection which can have only single element.

5. Static factory for n copies of specified object

nCopies(int n, T o) // returns List<T>

List<Integer> fifties = Collections.nCopies(3, 50);
Assert.assertTrue(Arrays.asList(50, 50, 50).equals(fifties));
 
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.addAll(Collections.nCopies(3, 50));

Assert.assertTrue(Arrays.asList(1, 2, 50, 50, 50).equals(list));

nCopies method creates an immutable List consisting of n copies of specified element. The new List returned just creates one copy of the specified object which is used to provide view for required length.

6. Conclusion

Collection static factories are extremely easy to use. They helps us create immutable collections by just calling a method. Using them is important too. For example, a method returning a collection must never return null instead it must return empty collection. Immutability is an important concepts which is leveraged in creation of this static factories.

Join the Newsletter

Download Complete Guide to Comparators in
1. Java 8
2. Map.Entry Interface
3. Spring
4. Google Guava
5. Apache Collections
with more than 60 examples. One book to know and learn it all.

    We respect your privacy. Unsubscribe at any time.

    Leave a Reply

    Your email address will not be published. Required fields are marked *