1

In Java 9, some new APIs have been added to facilitate the creation of immutable collections to reduce code complexity.

This episode's companion video: What's New in Java 9: Quickly Define Immutable Collections

regular writing

In the past, when we created some immutable collections, we usually wrote:

 // 不可变的Set
Set<String> set = new HashSet<>();
set.add("a");
set.add("b");
set.add("c");
set = Collections.unmodifiableSet(set);

// 不可变的List
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list = Collections.unmodifiableList(list);

Writing in Java8

In Java 8, using the Stream API can also be simplified, which can be evolved into this:

 Set<String> set = Collections.unmodifiableSet(Stream.of("a", "b", "c").collect(toSet()));
List<Integer> list = Collections.unmodifiableList(Stream.of(1, 2, 3).collect(toList()));

Writing in Java9

But now in Java 9, this operation has become simpler, just need this:

 Set<String> set = Set.of("a", "b", "c");
List<Integer> list = List.of(1, 2, 3);

At the same time, it is also supported for the following more complex collections, such as the Map type can also be written like this:

 Map<String, String> map = Map.of("a", "1", "b", "2", "c", "3");

It is to be noted that the parameters of Map.of appear in pairs of key and value, so the number of parameters must be an even number:

 Map.of()
Map.of(k1, v1)
Map.of(k1, v1, k2, v2)
Map.of(k1, v1, k2, v2, k3, v3)
...

Difference from asList

Seeing this, some people may ask, isn't there a convenient method like asXxx for collections before? Are they any different?

Here we take List.of and Arrays.asList as an example to list their similarities and differences:

  1. Introduced in Java 9 List.of creates immutable collections, while Arrays.asList is mutable collections
  2. List.of and Arrays.asList both do not allow add and remove elements, but Arrays.asList can call set to change the value, and List.of java.lang.UnsupportedOperationException Exception
  3. List.of does not allow null values, Arrays.asList can have null values

Well, today's sharing is here!

If you encounter difficulties in the learning process? You can join our high-quality technical exchange group , participate in exchanges and discussions, and learn and progress better!
This article is included in the "New Java Features Column" that I am serializing. This series should be written in the form of e-books. If you want to immerse yourself in reading and learning, you can visit the Web version: https://www.didispace.com/java -features/

https://www.didispace.com/java-features/

Welcome to my public account: Programmer DD. Learn about cutting-edge industry news for the first time, share in-depth technical dry goods, and obtain high-quality learning resources

程序猿DD
2.2k 声望2.8k 粉丝

作品:《Spring Cloud微服务实战》、SpringForAll社区、OpenWrite、Youtube中文配音