JAVA:不可变集作为列表

JAVA: ImmutableSet as List

我目前从函数调用 (getFeatures()) 中返回了一个 ImmutableSet,并且由于我的其余代码的结构将在稍后执行 - 将其更改为列表会容易得多。我试图转换它产生运行时异常。我还四处寻找将其转换为列表的函数调用,但无济于事。有没有办法做到这一点?我最近的[失败]尝试如下所示:

ImmutableSet<FeatureWrapper> wrappersSet =  getFeatures();
List<FeatureWrapper> wrappers = (List<FeatureWrapper>) wrappersSet;

我发现 wrapperSet.asList() 会给我一个 ImmutableList 但是我更喜欢一个可变列表

您不能将 Set<T> 转换为 List<T>。它们是完全不同的对象。只需使用此 copy constructor 从集合中创建一个新列表:

List<FeatureWrapper> wrappers = new ArrayList<>(wrappersSet);

ImmutableCollection 具有“asList”函数...

ImmutableList<FeatureWrapper> wrappersSet = getFeatures().asList();

返回类型 ImmutableList.

的奖励积分

如果你真的想要一个可变的 List,那么 答案就是你想要的。

由于 Guava-21 支持 java-8 您可以使用 streamcollectorImmutableSet 转换为 List:

ImmutableSet<Integer> intSet = ImmutableSet.of(1,2,3,4,5);
// using java-8 Collectors.toList()
List<Integer> integerList = intSet.stream().collect(Collectors.toList());
System.out.println(integerList); // [1,2,3,4,5]
integerList.removeIf(x -> x % 2 == 0); 
System.out.println(integerList); // [1,3,5] It is a list, we can add 
// and remove elements

我们可以将 ImmutableList#toImmutableList 与收集器一起使用,将 ImmutableList 转换为 ImmutableList : // 使用 ImmutableList#toImmutableList()

ImmutableList<Integer> ints = intSet.stream().collect(
                                     ImmutableList.toImmutableList()
                              );
System.out.println(ints); // [1,2,3,4,5]

最简单的方法是调用 ImmutableSet#asList

// using ImmutableSet#asList
ImmutableList<Integer> ints = intSet.asList();