HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions
  • Dark Mode

Immutable Collections with Factory Methods in Java 9

By Lokesh Gupta | Filed Under: 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 !!

TwitterFacebookLinkedinRedditPocket

About Lokesh Gupta

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

4
Leave a Reply

This comment form is under antispam protection
1 Comment threads
3 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
This comment form is under antispam protection
  Subscribe  
newest oldest most voted
Notify of
Saurabh

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

Vote Up0Vote Down  Reply
2 years ago
Lokesh Gupta

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

Vote Up0Vote Down  Reply
2 years ago
speakjava

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.”

Vote Up0Vote Down  Reply
2 years ago
Lokesh Gupta

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.

Vote Up0Vote Down  Reply
2 years ago

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

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Collections in Java
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Python Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

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 © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap

wpDiscuz