HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java 9 / Immutable Collections with Factory Methods in Java 9

Immutable Collections with Factory Methods in Java 9

Learn to create immutable collections such as immutable list, immutable set and immutable map using new factory methods in Java 9.

Table of Contents

Create Immutable List
Create Immutable Set
Create Immutable Map

Create Immutable List

Use List.of() static factory methods to create immutable lists. It has following different overloaded versions –

static <E> List<E>	of()
static <E> List<E>	of(E e1)
static <E> List<E>	of(E e1, E e2)
static <E> List<E>	of(E e1, E e2, E e3)
static <E> List<E>	of(E e1, E e2, E e3, E e4)
static <E> List<E>	of(E e1, E e2, E e3, E e4, E e5)
static <E> List<E>	of(E e1, E e2, E e3, E e4, E e5, E e6)
static <E> List<E>	of(E e1, E e2, E e3, E e4, E e5, E e6, E e7)
static <E> List<E>	of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8)
static <E> List<E>	of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9)
static <E> List<E>	of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10)
//varargs
static <E> List<E>	of(E... elements)

The List instances created by these methods have the following characteristics:

  1. These lists are immutable. Elements cannot be added, removed, or replaced in these lists. Calling any mutator method (i.e. add, addAll, clear, remove, removeAll, replaceAll) will always cause UnsupportedOperationException to be thrown.
  2. They do not allow null elements. Attempts to add null elements result in NullPointerException.
  3. They are serializable if all elements are serializable.
  4. The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.

Lets see few examples of usage of immutable list.

package com.howtodoinjava;

import java.util.List;

public class ImmutableCollections 
{
    public static void main(String[] args) 
    {
        List<String> names = List.of("Lokesh", "Amit", "John");
        
        //Preserve the elements order
        System.out.println(names);
        
        //names.add("Brian"); //UnsupportedOperationException occured
        
        //java.lang.NullPointerException
        //List<String> names2 = List.of("Lokesh", "Amit", "John", null); 
    }
}

Output:

[Lokesh, Amit, John]

Create Immutable Set

Set behave very similar to List with only few differences. e.g.

  1. Set do not allow duplicate elements as well. Any duplicate element passed will result in IllegalArgumentException.
  2. The iteration order of set elements is unspecified and is subject to change.

All Set factory methods have the same signature as List.

static <E> Set<E>	of()
static <E> Set<E>	of(E e1)
static <E> Set<E>	of(E e1, E e2)
static <E> Set<E>	of(E e1, E e2, E e3)
static <E> Set<E>	of(E e1, E e2, E e3, E e4)
static <E> Set<E>	of(E e1, E e2, E e3, E e4, E e5)
static <E> Set<E>	of(E e1, E e2, E e3, E e4, E e5, E e6)
static <E> Set<E>	of(E e1, E e2, E e3, E e4, E e5, E e6, E e7)
static <E> Set<E>	of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8)
static <E> Set<E>	of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9)
static <E> Set<E>	of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10)
//varargs
static <E> Set<E>	of(E... elements)

Let’s see few examples of immutable sets.

import java.util.Set;

public class ImmutableCollections {
    public static void main(String[] args) {
        Set<String> names = Set.of("Lokesh", "Amit", "John");
        
        //Elements order not fixed
        System.out.println(names);
        
        //names.add("Brian"); //UnsupportedOperationException occured
        
        //java.lang.NullPointerException
        //Set<String> names2 = Set.of("Lokesh", "Amit", "John", null); 
        
        //java.lang.IllegalArgumentException
        //Set<String> names3 = Set.of("Lokesh", "Amit", "John", "Amit"); 
    }
}

Create Immutable Map

Map factory methods are same as List or Set overloaded factory methods. Only difference is that the signatures of the of methods take alternating keys and values as arguments. e.g.

static <K,V> Map<K,V>	of()
static <K,V> Map<K,V>	of(K k1, V v1)
static <K,V> Map<K,V>	of(K k1, V v1, K k2, V v2)
...
...
static <K,V> Map<K,V>	ofEntries(Map.Entry<? extends K,? extends V>... entries)

Java 9 also provide a special method for creating Map entry instance.

static <K,V> Map.Entry<K,V>	entry​(K k, V v)

Let’s take an example of creating immutable Map in java 9.

import java.util.Map;

public class ImmutableCollections {
    public static void main(String[] args) {
        Map<String, String> names = Map.ofEntries(
                Map.entry("1", "Lokesh"),
                Map.entry("2", "Amit"),
                Map.entry("3", "Brian"));
        
        System.out.println(names);
        
        //UnsupportedOperationException
        //names.put("2", "Ravi");
    }
}

Output:

{1=Lokesh, 2=Amit, 3=Brian}

Clearly, new factory methods to create immutable collections in java 9 are very much readable and easy to use.

Drop me your opinion on these immutable collections in comments section.

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Saurabh

    August 1, 2017

    Hi Lokesh,
    What is need of so many overloaded methods in List interface. Having method with varags parameter can take care of everything.

    • Lokesh Gupta

      August 1, 2017

      In fact, I also find it weird. I will try to find more reasoning behind it.

      • speakjava

        August 3, 2017

        The reason is performance. We could indeed have just one varargs method that would deal with all number of parameters. The problem is that this requires the creation of an array, copying of parameters to the elements of that array and then garbage collection of the array. JEP 269, which details this feature explains that, “It is not a goal to support high-performance, scalable collections with arbitrary numbers of elements. The focus is on small collections.”

        • Lokesh Gupta

          August 3, 2017

          Thank you for jumping into the discussion. Yes, you are right about improved performance of small collections. For others to read more, please go to JEP 269.

Comments are closed on this article!

Search Tutorials

Java 9 Tutorial

  • Java 9 – Introduction
  • Java 9 – Compact Strings
  • Java 9 – Modules
  • Java 9 – JShell
  • Java 9 – Stream of Dates
  • Java 9 – Stream API Improvements
  • Java 9 – Immutable Collections
  • Java 9 – Interface Private Methods

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces