将单个元素添加到不可变集合的有效且优雅的方法是什么?

Max*_*Max 25 java guava

我有一个Set<Integer>可能包含许多元素的不可变集(强制转换为a ).我需要一个Collection,其中包含该集合中的元素以及一个附加元素.我有kludgy代码来复制集合,然后附加元素,但我正在寻找使事情尽可能高效的正确方法.

我有番石榴可用,但我不需要它.

Nik*_* B. 35

不确定性能,但你可以使用番石榴ImmutableSet.Builder:

import com.google.common.collect.ImmutableSet

// ...
Set<Integer> newSet = new ImmutableSet.Builder<Integer>()
                                .addAll(oldSet)
                                .add(3)
                                .build();
Run Code Online (Sandbox Code Playgroud)

当然你也可以为自己写一个帮助方法:

public static <T> Set<T> setWith(Set<T> old, T item) {
  return new ImmutableSet.Builder<T>().addAll(old).add(item).build();
}

// ...
Set<Integer> newSet = setWith(oldSet, 3);
Run Code Online (Sandbox Code Playgroud)


Bri*_*ice 6

使用 Java 8,您还可以使用流来实现该效果

Stream.concat(oldSet.stream(),
              Stream.of(singleElement))
      .collect(Collectors.toSet())
Run Code Online (Sandbox Code Playgroud)

顺便说一下,自 JDK 10 起,Collectors还允许累积为不可变类型(与静态工厂创建的类型相同,例如Set.of()):

Stream.concat(oldSet.stream(),
              Stream.of(singleElement))
      .collect(Collectors.toUnmodifiableSet())
Run Code Online (Sandbox Code Playgroud)


Dar*_*roy 5

您可能会考虑Sets.union()。施工会更快,但使用起来会更慢。

public static <T> Set<T> setWith(Set<T> old, T item) {
  return Sets.union(old, Collections.singleton(item);
}
Run Code Online (Sandbox Code Playgroud)

(com.google.common.collect.Sets和java.util.Collections)