Java 9 static factory method to create immutable collection

Java 9 introduced new factory methods in the collections API to make it easier for developers to create immutable collections.

In this article, I'll first explain the motivation for including the new factory method, and then describe all the methods, their usage, and implementation details.

Tell me, how can I create an immutable Map with initial key-value pairs in Java 8 or less?

But that's too verbose, isn't it? Can we do something else?

Actually you have another option. You can use the double brace initialization syntax to initialize an immutable Map like this:

It's a bit verbose, but expensive. The way the double curly braces technique works is to create an anonymous inner class and provide an instance initializer block that calls all of the above put() statements.

So every time you create a map this way, you're creating a non-reusable anonymous class whose object reference is held by the ClassLoader. This can lead to memory leaks and serialization issues.

You can read more about the double brace technique and its problems here and here.

Therefore, it is best to avoid the double brace technique. In the end, we have the only option, which is to create an empty map and add key-value pairs one by one.

Now, compare the way Java creates and initializes a Map with the Scala version:

Kotlin version:

You can see how easy it is to create and initialize immutable collections in languages ​​like Scala and Kotlin.

Java does need a less verbose way to initialize immutable collections, so Java 9 introduced static factory methods in the List, Set and Map interfaces to create immutable collections.

Let's see how the new factory method works in Java 9:

An immutable collection that cannot enter null, where map has another unique constructor:

Methods in which there cannot be duplicate values:

The new factory method is much easier to use. When we use immutable collections, they definitely make our life easier.

In fact, I want to say that this greatly increases the difficulty of interviewing newcomers. After all, java will soon join the release army. With so much content, let’s see what happens below:

 

Original link:

https://www.callicoder.com/java-9-immutable-collections-factory-methods/

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324954031&siteId=291194637
Recommended