JAVA: ImmutableSet as List

6.7k Views Asked by At

I currently get returned an ImmutableSet from a function call (getFeatures()) and due to the structure of the rest of my code to be executed later on- it would be much easier to change this to a List. I have tried to cast it which produces a runtime exception. I have also looked around for a function call to convert it to a list to no avail. Is there a way to do this? My most recent [failed] attempt is shown below:

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

I have found wrapperSet.asList() which will give me an ImmutableList however i would much rather prefer a mutable list

3

There are 3 best solutions below

1
On BEST ANSWER

You can't cast a Set<T> into a List<T>. They are entirely-different objects. Just use this copy constructor which creates a new list out of a collection:

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

Since Guava-21 supports java-8 you can use stream and collector to convert an ImmutableSet to a 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

We can use ImmutableList#toImmutableList with collectors to convert an ImmutableList to a ImmutableList : // using ImmutableList#toImmutableList()

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

And the easiest way is to call ImmutableSet#asList

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

ImmutableCollection has the "asList" function...

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

Bonus points that the returned type an ImmutableList.

If you really wanted a mutable List though, then Vivin's answer is what you want.