Java 9 features – Collections Update

Finally, Java 9 is out and it’s high time to go through and discuss the issues of previous JDK releases and discuss the benefits of recently release JDK 9 features. Changing in Collections is one of the features that is of particular interest to developers and is discussed in this article.

Some of the previous collections related posts are given below:

Collections in Java

Map Interface in Java

ArrayList in Java

Benefits of Collections

  • Widely used in java and helps to gather data in many ways in your applications
  • Provides various useful ways to manipulate the data
  • Plenty of collection interfaces that represent the abstract concepts of a List, Set and Map

Issues with Collections in Java 8

  • There is no simple way to create a collection with predefined data.
  • Some extra line of code is required if you want a collection to be immutable

Here are examples to make a collection immutable in Java 8.
1. List Example

2. Map Example

In order to create an immutable list of four values, one need six lines of code. Let’s have a look how JDK 9 resolved this issue.

New Methods for Collections

1. List Example

2. Map Example

Java 9 also introduced a set of new methods to the Collections Framework. Let’s start by looking at the problem these
methods are trying to solve, by instantiating an array of String with a few values and converting array to a list.
Problem :

Solution :

If you will try to add another value into the list it will throw java.lang.UnsupportedOperationException Exception. To resolve this issue

Static Entry Method for Maps

Handling varargs in Maps is bit tricky because you need both keys and values. Therefore, JDK 9 introduce a varargs method Map.Entry<K,V> and adding a static entry methods that constructs it. Find the example below.

JDK 9 also introduced some additional methods so that you can’t pass duplicate arguments when you create a Set and can’t you pass duplicate keys when you create Map. A null value is not allowed for any collection method. We will cover these methods at later stages. Please write your suggestion in comment box.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.