DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Java
  4. Java 9: Factory Methods to Create Immutable Collections

Java 9: Factory Methods to Create Immutable Collections

Creating immutable collections will be way more convenient in Java 9, thanks to the newly added factory methods in collection interfaces.

Siva Prasad Rao Janapati user avatar by
Siva Prasad Rao Janapati
·
Feb. 21, 17 · Tutorial
Like (26)
Save
Tweet
Share
17.06K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we will see another JDK 9 feature — creating immutable collections. Until Java 8, if we wanted to create immutable collections, we used to call unmodifiableXXX() methods on java.util.Collections. For example,  To create an unmodifiable list, we should write:

jshell> List<String> list = new ArrayList<String>();
list ==> []

jshell> list.add("Smart")
$2 ==> true

jshell> list.add("Techie")
$3 ==> true

jshell> System.out.println("The values are: "+ list);
The list values are: [Smart, Techie]

jshell> // make the list unmodifiable

jshell>    List<String> immutablelist = Collections.unmodifiableList(list);
immutablelist ==> [Smart, Techie]

jshell> // try to modify the list

jshell>    immutablelist.add("Smart_1")
|  java.lang.UnsupportedOperationException thrown:
|        at Collections$UnmodifiableCollection.add (Collections.java:1056)
|        at (#6:1)

jshell>


The above code is too verbose to create a simple unmodifiable List. As Java is adopting functional programming style, Java 9 came up with convenient, more compacted factory methods to create unmodifiable collections, as seen in JEP 269. Let us see how that works.

Create Empty List

jshell> List immutableList = List.of();
immutableList ==> []

//Add an item to the list
jshell> immutableList.add("Smart")
|  Warning:
|  unchecked call to add(E) as a member of the raw type java.util.List
|  immutableList.add("Smart")
|  ^------------------------^
|  java.lang.UnsupportedOperationException thrown:
|        at ImmutableCollections.uoe (ImmutableCollections.java:70)
|        at ImmutableCollections$AbstractImmutableList.add (ImmutableCollections.java:76)
|        at (#2:1)


Create Non-Empty List

jshell> List immutableList = List.of("Smart","Techie");
immutableList ==> [Smart, Techie]

jshell> //add an item to the list

jshell> immutableList.add("Smart_1")
|  Warning:
|  unchecked call to add(E) as a member of the raw type java.util.List
|  immutableList.add("Smart_1")
|  ^--------------------------^
|  java.lang.UnsupportedOperationException thrown:
|        at ImmutableCollections.uoe (ImmutableCollections.java:70)
|        at ImmutableCollections$AbstractImmutableList.add (ImmutableCollections.java:76)
|        at (#2:1)

jshell>


Create Non-Empty Map

jshell> Map immutableMap = Map.of(1,"Smart",2,"Techie");
immutableMap ==> {1=Smart, 2=Techie}

//Get item from Map
jshell> immutableMap.get(1);
$2 ==> "Smart"

//Add item to map
jshell> immutableMap.put(3,"Smart_1");
|  Warning:
|  unchecked call to put(K,V) as a member of the raw type java.util.Map
|  immutableMap.put(3,"Smart_1
|  ^---------------------------^
|  java.lang.UnsupportedOperationException thrown:
|        at ImmutableCollections.uoe (ImmutableCollections.java:70)
|        at ImmutableCollections$AbstractImmutableMap.put (ImmutableCollections.java:557)
|        at (#3:1)

jshell>


If you look at the above Java 9 factory method, the code is a simple one liner to create immutable collections. In an upcoming article, we will see another Java 9 feature. Stay tuned!

Java (programming language) Factory (object-oriented programming)

Published at DZone with permission of Siva Prasad Rao Janapati, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Distributed SQL: An Alternative to Database Sharding
  • How To Use Terraform to Provision an AWS EC2 Instance
  • Understanding gRPC Concepts, Use Cases, and Best Practices
  • Spring Cloud: How To Deal With Microservice Configuration (Part 1)

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: