我目前从函数调用(getFeatures())返回一个不可变集,并且由于我稍后要执行的其余代码的结构 - 将其更改为列表会容易得多。我试图强制转换它,这会产生运行时异常。我还四处寻找函数调用以将其转换为列表无济于事。有没有办法做到这一点?我最近的[失败]尝试如下所示:
ImmutableSet<FeatureWrapper> wrappersSet = getFeatures();
List<FeatureWrapper> wrappers = (List<FeatureWrapper>) wrappersSet;
我找到了wrapperSet.asList(),它会给我一个不可变列表,但我宁愿选择一个可变列表
您不能将Set<T>
转换为List<T>
。它们是完全不同的对象。只需使用此复制构造函数,它从集合中创建一个新列表:
List<FeatureWrapper> wrappers = new ArrayList<>(wrappersSet);
ImmutableCollection
具有"asList"函数...
ImmutableList<FeatureWrapper> wrappersSet = getFeatures().asList();
返回的类型ImmutableList
的奖励积分。
如果你真的想要一个可变的List
,那么Vivin的答案就是你想要的。
由于Guava-21
支持java-8
您可以使用stream
和collector
将ImmutableSet
转换为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();