Skip to content

集合转换:从一种集合到另一种

转换总览

数组 ←→ List ←→ Set

         Map

数组 ↔ List

数组 → List

java
String[] array = {"a", "b", "c"};

// 方式 1:Arrays.asList(最常用)
List<String> list = Arrays.asList(array);

// 方式 2:List.of(JDK 9+,不可变)
List<String> immutable = List.of("a", "b", "c");

// 方式 3:Stream
List<String> stream = Arrays.stream(array).collect(Collectors.toList());

List → 数组

java
List<String> list = Arrays.asList("a", "b", "c");

// 方式 1:toArray()(返回 Object[])
Object[] arr1 = list.toArray();

// 方式 2:toArray(T[])(推荐,返回具体类型)
String[] arr2 = list.toArray(new String[0]); // 数组大小为 0 即可
String[] arr3 = list.toArray(String[]::new);  // 方法引用

List ↔ Set

List → Set(去重)

java
List<String> list = Arrays.asList("a", "b", "a", "c");

Set<String> hashSet = new HashSet<>(list);         // 无序去重
Set<String> linkedSet = new LinkedHashSet<>(list); // 保持首次出现顺序
Set<String> treeSet = new TreeSet<>(list);         // 自然排序

Set → List

java
Set<String> set = new HashSet<>(Arrays.asList("a", "b", "c"));

List<String> list = new ArrayList<>(set); // 构造函数
list.addAll(set);                      // addAll

Map 与其他集合

Map → Set/List

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

// Map → 所有 key
Set<String> keys = map.keySet();

// Map → 所有 value
Collection<Integer> values = map.values();

// Map → 所有 entry
Set<Map.Entry<String, Integer>> entries = map.entrySet();

List/Set → Map

java
List<String> list = Arrays.asList("apple", "banana", "apricot");

// List → Map(按字符串长度作为 key)
Map<Integer, String> byLength = list.stream()
    .collect(Collectors.toMap(
        String::length,   // key
        s -> s,           // value
        (a, b) -> a      // 冲突时保留前者
    ));
// {5=apple, 6=banana, 7=apricot}

Arrays.asList 的陷阱

java
// asList 返回的是「固定大小」列表,不是「不可变」列表
String[] array = {"a", "b", "c"};
List<String> list = Arrays.asList(array);

// ✅ 可以修改元素
list.set(0, "x"); // OK
System.out.println(Arrays.toString(array)); // [x, b, c](原数组也被改了!)

// ❌ 不能增删
list.add("d"); // UnsupportedOperationException
list.remove(0); // UnsupportedOperationException

常见模式

去重

java
// 数组去重
String[] distinct = Arrays.stream(array)
    .distinct()
    .toArray(String[]::new);

// List 去重
List<String> distinct = list.stream().distinct().collect(Collectors.toList());

不可变副本

java
// List 的不可变副本
List<String> immutable = Collections.unmodifiableList(list);
List<String> immutable2 = List.copyOf(list); // JDK 10+

// Set 的不可变副本
Set<String> immutableSet = Collections.unmodifiableSet(set);
Set<String> immutableSet2 = Set.copyOf(set); // JDK 10+

// Map 的不可变副本
Map<String, Integer> immutableMap = Collections.unmodifiableMap(map);
Map<String, Integer> immutableMap2 = Map.copyOf(map); // JDK 10+

总结

转换方法
数组 → ListArrays.asList(arr)
List → 数组list.toArray(new String[0])
List → Setnew HashSet<>(list)
Set → Listnew ArrayList<>(set)
Map → keymap.keySet()
Map → valuemap.values()
Map → entrymap.entrySet()

相关链接

基于 VitePress 构建