Home> Java> javaTutorial> body text

How to initialize immutable collection in Java 9?

王林
Release: 2023-08-20 23:37:52
forward
704 people have browsed it

在Java 9中如何初始化不可变集合?

Java 9 providesfactory methodsto createimmutablelists,collectionsandmap. It can be used to createemptyornon-emptycollection objects. In Java 8 and previous versions, we can use utility methods of collection classes such asunmodifiableXXXto createimmutablecollection objects. If we need to create an immutable list, we can use theCollections.unmodifiableList()method.

These factory methods allow us to easily initializeimmutablecollections, whether they areemptyornon-empty.

Initialization of immutable list:

List immutableEmptyList = List.of();
Copy after login

In the above code, we initialize an emptyimmutableList.

Initializing an immutable collection:

Set immutableEmptySet = Set.of();
Copy after login

In the above code, we initialize an emptyimmutableSet.

Initialize immutable map:

Map immutableEmptyMap = Map.of();
Copy after login

In the above, we have initialized an empty,immutableMap.

Example

import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; public class ImmutableCollectionTest { public static void main(String args[]) { List list8 = new ArrayList(); list8.add("INDIA"); list8.add("AUSTRALIA"); list8.add("ENGLAND"); list8.add("NEWZEALAND"); List immutableList8 = Collections.unmodifiableList(list8); immutableList8.forEach(System.out::println); System.out.println(); List immutableList = List.of("INDIA", "AUSTRALIA", "ENGLAND", "NEWZEALAND"); immutableList.forEach(System.out::println); System.out.println(); Set immutableSet = Set.of("INDIA", "AUSTRALIA", "ENGLAND", "NEWZEALAND"); immutableSet.forEach(System.out::println); System.out.println(); Map immutableMap = Map.of("INDIA", "India", "AUSTRALIA", "Australia", "ENGLAND", "England", "NEWZEALAND", "Newzealand"); immutableMap.forEach((key, value) -> System.out.println(key + " : " + value)); System.out.println(); } }
Copy after login

Output

INDIA AUSTRALIA ENGLAND NEWZEALAND INDIA AUSTRALIA ENGLAND NEWZEALAND AUSTRALIA ENGLAND NEWZEALAND INDIA AUSTRALIA : Australia ENGLAND : England NEWZEALAND : Newzealand INDIA : India 
Copy after login

The above is the detailed content of How to initialize immutable collection in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!