Java 9 Factory Method for Collections: List, Set, Map

java-9-factory-method-for-immutable-collections-list-set-map-feature-image

Java 9 provides new static factory methods for creating instances of collections and maps conveniently with small number of elements. In this tutorial, we’re gonna look at how to create List, Set, Map with Java 9 Factory Method for Collections.

I. List

To create a List, we use those static methods:


// for empty list
static  List of()
// for list containing one element
static  List of(E e1)
// for list containing two element
static  List of(E e1, E e2)
// ...
// for list containing an arbitrary number of elements
static  List of(E... elements)

For example:


List immutableList = List.of();
immutableList = List.of("one", "two", "three");

If we try to create list with null element, a java.lang.NullPointerException will be thrown:


List immutableList = List.of("one", "two", "three", null);

Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.Objects.requireNonNull(Objects.java:221)
	at java.base/java.util.ImmutableCollections$ListN.(ImmutableCollections.java:233)
	at java.base/java.util.List.of(List.java:859)

Because the list created with static factory method is immutable, so if we try to add an element to list, it also throws an java.lang.UnsupportedOperationException


List immutableList = List.of("one", "two", "three");
immutableList.add("four");

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:70)
	at java.base/java.util.ImmutableCollections$AbstractImmutableList.add(ImmutableCollections.java:76)

Solution for problems above:


List mutableList = new ArrayList(List.of("one", "two", "three"));
mutableList.add("four");
mutableList.add(null);

// Result: 
[one, two, three, four, null]

II. Set

To create a Set, we use those static methods:


// for empty Set
static  Set of()
// for Set containing one element
static  Set of(E e1)
// for Set containing two element
static  Set of(E e1, E e2)
// ...
// for Set containing an arbitrary number of elements
static  Set of(E... elements)

For example:


Set immutableSet = Set.of();
immutableSet = Set.of("one", "two", "three");

If we try to create set with null element, a java.lang.NullPointerException will be thrown:


Set immutableSet = Set.of("one", "two", "three", null );

Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.ImmutableCollections$SetN.probe(ImmutableCollections.java:520)
	at java.base/java.util.ImmutableCollections$SetN.(ImmutableCollections.java:460)
	at java.base/java.util.Set.of(Set.java:520)

Because the set created with static factory method is immutable, so if we try to add an element to set, it also throws an java.lang.UnsupportedOperationException


Set immutableSet = Set.of("one", "two", "three");
immutableSet.add("four");

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:70)
	at java.base/java.util.ImmutableCollections$AbstractImmutableSet.add(ImmutableCollections.java:280)

Solution for problems above:


Set mutableSet = new HashSet(Set.of("one", "two", "three"));
mutableSet.add("four");
mutableSet.add(null);

// Result: 
[null, four, one, two, three]

III. Map

1. Map.of()

To create a Map, we use those static methods:


// for empty Map
static  Map of()
// for Map containing a single mapping
static  Map of(K k1, V v1)
// for Map containing two mappings
static  Map of(K k1, V v1, K k2, V v2)
// ...
// for Map containing up to ten mappings
static  Map of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5,
                               K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10)

For example:


Map immutableMap = Map.of();
immutableMap = Map.of(1, "one", 2, "two", 3, "three");

If we try to create Map with null value, a java.lang.NullPointerException will be thrown:


Map immutableMap = Map.of(1, "one", 2, "two", 3, "three", 4, null );

Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.Objects.requireNonNull(Objects.java:221)
	at java.base/java.util.ImmutableCollections$MapN.(ImmutableCollections.java:677)
	at java.base/java.util.Map.of(Map.java:1372)

Because the map created with static factory method is immutable, so if we try to put (key,value) pair to map, it also throws an java.lang.UnsupportedOperationException


Map immutableMap = Map.of(1, "one", 2, "two", 3, "three");
immutableMap.put(4, "four");

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:70)
	at java.base/java.util.ImmutableCollections$AbstractImmutableMap.put(ImmutableCollections.java:557)

Solution for problems above:


Map mutableMap = new HashMap(Map.of(1, "one", 2, "two", 3, "three"));

mutableMap.put(4, "four");
mutableMap.put(5, null);

// Result:
{1=one, 2=two, 3=three, 4=four, 5=null}

2. Map.ofEntries()

If we wanna create a Map with more than ten mappings, there is another way: Using Map.ofEntries() method.


static  Map ofEntries(Entry... entries)

To use that method, we use a method for boxing keys and values, suitable for static import:


static  Entry entry(K k, V v)

So, this is way to use them:


Map newImmutableMap = Map.ofEntries(Map.entry(1, "one"), Map.entry(2, "two"), Map.entry(3, "three"));

IV. Source Code


package com.javasampleapproach.immutablecollections;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MainApp {

	public static void main(String[] args) {

		// List
		System.out.println("--- List ---");
		List immutableList = List.of();
		System.out.println(immutableList);

		immutableList = List.of("one", "two", "three"/* , null */);
		System.out.println(immutableList);

		// immutableList.add("four");

		List mutableList = new ArrayList(List.of("one", "two", "three"));
		mutableList.add("four");
		mutableList.add(null);
		System.out.println(mutableList);

		// Set
		System.out.println("--- Set ---");
		Set immutableSet = Set.of();
		System.out.println(immutableSet);

		immutableSet = Set.of("one", "two", "three"/* , null */);
		System.out.println(immutableSet);

		// immutableSet.add("four");

		Set mutableSet = new HashSet(Set.of("one", "two", "three"));
		mutableSet.add("four");
		mutableSet.add(null);
		System.out.println(mutableSet);

		// Map
		System.out.println("--- Map ---");
		Map immutableMap = Map.of();
		System.out.println(immutableMap);

		immutableMap = Map.of(1, "one", 2, "two", 3, "three"/* , 4, null */);
		System.out.println(immutableMap);

		// immutableMap.put(4, "four");

		Map mutableMap = new HashMap(Map.of(1, "one", 2, "two", 3, "three"));
		System.out.println(mutableMap);

		mutableMap.put(4, "four");
		mutableMap.put(5, null);
		System.out.println(mutableMap);

		// Map with Entry
		System.out.println("--- Map Entry ---");
		Map newImmutableMap = Map.ofEntries();
		System.out.println(newImmutableMap);

		newImmutableMap = Map.ofEntries(Map.entry(1, "one"), Map.entry(2, "two"), Map.entry(3, "three"));
		System.out.println(newImmutableMap);
		
	}
}

Run the code, the result in Console Window:


--- List ---
[]
[one, two, three]
[one, two, three, four, null]
--- Set ---
[]
[one, two, three]
[null, four, one, two, three]
--- Map ---
{}
{2=two, 3=three, 1=one}
{1=one, 2=two, 3=three}
{1=one, 2=two, 3=three, 4=four, 5=null}
--- Map Entry ---
{}
{2=two, 3=three, 1=one}


By grokonez | March 5, 2017.

Last updated on April 22, 2021.



Related Posts


Got Something To Say:

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

*