JAVA: ImmutableSet as List

I am currently returning an ImmutableSet from a function call (getFeatures ()), and due to the structure of the rest of my code to be executed later, it would be much easier to change this to a list. I tried using it, which throws a runtime exception. I also looked at the function call to convert it to a list to no avail. Is there a way to do this? My last failed attempt is shown below:

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

      

I found wrapperSet.asList () which will give me ImmutableList, but I would rather change the list

+3


source to share


3 answers


You cannot draw Set<T>

in List<T>

. These are completely different objects. Just use the copy constructor , which creates a new list from the collection:



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

      

+8


source


ImmutableCollection

has a function asList ...

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

      



The bonus indicates that the return type is a ImmutableList

.

If you really want mutable List

, then Vivin's answer is what you want.

+4


source


As the Guava-21

supports java-8

, you can use stream

and collector

to convert ImmutableSet

to 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 ImmutableList

to ImmutableList

: // use 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


source







All Articles