我有一个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)
使用 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)
您可能会考虑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)