Java中 创建不可变集合

常规写法

以往我们创建一些不可变集合的时候,通常是这样写的:

// 不可变的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);

Java8的写法

在Java 8的时候,利用Stream API还能简化一下,可以演变成这样:

Set<String> set = Collections.unmodifiableSet(Stream.of("a", "b", "c").collect(toSet()));

List<Integer> list = Collections.unmodifiableList(Stream.of(1, 2, 3).collect(toList()));

Java9的写法

而现在到了Java 9,这一操作变的更为简单,只需要这样:

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

同时,对于一下更复杂的集合也一样支持,比如Map类型也可以这样写:

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

就是要注意下,Map.of的参数是key和value成对出现的,所以参数数量一定是偶数:

Map.of()

Map.of(k1, v1)

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

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

...

与asList的区别

看到这里,可能有的人会问了,之前不是对于集合有asXxx这样的方便方法了么?他们有啥区别吗?

这里就以 List.of 和 Arrays.asList 为例,给大家列一下它们的异同:

Java 9中推出 List.of 创建的是不可变集合,而 Arrays.asList 是可变集合

List.of 和 Arrays.asList 都不允许add和remove元素,但 Arrays.asList 可以调用set更改值,而 List.of 不可以,会报 java.lang.UnsupportedOperationException 异常

List.of 中不允许有null值, Arrays.asList 中可以有null值

相关推荐
programer_331 小时前
本地手动创建一个MCP(windows环境)
windows·python·ai·mcp·cherry studio
曹牧1 小时前
Java:List<Map<String, String>>转换为字符串
java·开发语言·windows
Unstoppable222 小时前
代码随想录算法训练营第 56 天 | 拓扑排序精讲、Dijkstra(朴素版)精讲
java·数据结构·算法·
qinyia2 小时前
WisdomSSH解决docker run命令中log-opt参数不支持导致的容器创建失败问题
java·docker·eureka
电饭叔2 小时前
不含Luhn算法《python语言程序设计》2018版--第8章14题利用字符串输入作为一个信用卡号之二(识别卡号有效)
java·python·算法
观音山保我别报错3 小时前
列表,元组,字典
开发语言·python
小付爱coding3 小时前
Claude Code安装教程【windows版本】
java·git·python
**蓝桉**3 小时前
数组的执行原理,java程序的执行原理
java·开发语言
YDS8293 小时前
MyBatis-Plus精讲 —— 从快速入门到项目实战
java·后端·spring·mybatis·mybatis-plus
BIBI20493 小时前
Windows 下 Git 常规操作教程:命令行与 TortoiseGit
windows·git·tortoisegit·配置·版本控制·入门指南