List和Map的几种初始化方法

目录

List初始化方法

使用ArrayList的构造方法初始化

使用Arrays.asList()方法初始化

使用Collections.addAll()方法初始化:

[使用List.of()方法初始化(Java 9及以上版本)](#使用List.of()方法初始化(Java 9及以上版本))

使用Stream的collect()方法初始化

Map的初始化方法

使用HashMap的构造方法初始化

[使用Collections.singletonMap()方法初始化(创建只包含一个键值对的不可变 Map)](#使用Collections.singletonMap()方法初始化(创建只包含一个键值对的不可变 Map))

[使用双括号初始化(Double Brace Initialization)](#使用双括号初始化(Double Brace Initialization))

[使用Map.of()方法初始化(Java 9及以上版本,创建只包含有限个键值对的不可变 Map)](#使用Map.of()方法初始化(Java 9及以上版本,创建只包含有限个键值对的不可变 Map))

[使用Stream的collect()方法初始化(通过收集器生成 Map)](#使用Stream的collect()方法初始化(通过收集器生成 Map))

[使用Map.entry()方法初始化(Java 9及以上版本,创建只包含一个键值对的不可变 Map)](#使用Map.entry()方法初始化(Java 9及以上版本,创建只包含一个键值对的不可变 Map))


List初始化方法

使用ArrayList的构造方法初始化

java 复制代码
List<String> list1 = new ArrayList<>();

使用Arrays.asList()方法初始化

java 复制代码
List<String> list2 = Arrays.asList("a", "b", "c");

使用Collections.addAll()方法初始化

java 复制代码
List<String> list3 = new ArrayList<>();
Collections.addAll(list3, "a", "b", "c");

使用List.of()方法初始化(Java 9及以上版本)

java 复制代码
List<String> list4 = List.of("a", "b", "c");

使用Stream的collect()方法初始化

java 复制代码
List<String> list5 = Stream.of("a", "b", "c").collect(Collectors.toList());
java 复制代码
List<String> list6 = new ArrayList<>() {{
    add("a");
    add("b");
    add("c");
}};

Map的初始化方法

使用HashMap的构造方法初始化

java 复制代码
Map<String, Integer> map1 = new HashMap<>();

使用Collections.singletonMap()方法初始化(创建只包含一个键值对的不可变 Map)

java 复制代码
Map<String, Integer> map2 = Collections.singletonMap("key", 1);

使用双括号初始化(Double Brace Initialization)

java 复制代码
Map<String, Integer> map3 = new HashMap<>() {{
    put("key1", 1);
    put("key2", 2);
    // 可以连续添加多个键值对
}};

使用Map.of()方法初始化(Java 9及以上版本,创建只包含有限个键值对的不可变 Map)

java 复制代码
Map<String, Integer> map4 = Map.of("key1", 1, "key2", 2);

使用Stream的collect()方法初始化(通过收集器生成 Map)

java 复制代码
Map<String, Integer> map5 = Stream.of(
        new AbstractMap.SimpleEntry<>("key1", 1),
        new AbstractMap.SimpleEntry<>("key2", 2)
).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

使用Map.entry()方法初始化(Java 9及以上版本,创建只包含一个键值对的不可变 Map)

java 复制代码
Map<String, Integer> map6 = Map.entry("key", 1);

以上是一些常见的 Map 集合初始化方法,每种方法都有其适用的场景和特点,根据实际需求选择合适的方法即可。

相关推荐
独好紫罗兰1 天前
对python的再认识-基于数据结构进行-a003-列表-排序
开发语言·数据结构·python
wuhen_n1 天前
JavaScript内置数据结构
开发语言·前端·javascript·数据结构
2401_841495641 天前
【LeetCode刷题】二叉树的层序遍历
数据结构·python·算法·leetcode·二叉树··队列
独好紫罗兰1 天前
对python的再认识-基于数据结构进行-a002-列表-列表推导式
开发语言·数据结构·python
2401_841495641 天前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
数智工坊1 天前
【数据结构-树与二叉树】4.5 线索二叉树
数据结构
数智工坊1 天前
【数据结构-树与二叉树】4.3 二叉树的存储结构
数据结构
独好紫罗兰1 天前
对python的再认识-基于数据结构进行-a004-列表-实用事务
开发语言·数据结构·python
铉铉这波能秀1 天前
LeetCode Hot100数据结构背景知识之列表(List)Python2026新版
数据结构·leetcode·list
历程里程碑1 天前
Linux20 : IO
linux·c语言·开发语言·数据结构·c++·算法