Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Immutable to mutable list Java, is there any alternative? [closed]

I have a method that returns an Immutable list. I want to add elements to it and that's why have to convert it to a mutable list. Currently, I am creating a new ArrayList out of the Immutable list as follows:

final List<someDTO> mutableList = new ArrayList<>(someDTO.getImmutableList());

Is there any better way of doing it like using some collections copy method, java streams, or anything like that?

like image 369
shelholmes221 Avatar asked Dec 13 '18 18:12

shelholmes221


People also ask

Can you add element to immutable list Java?

We cannot add, update or remove elements in an immutable List . An immutable List is completely immutable only if its containing objects are also immutable.

Are asList arrays immutable?

util. Arrays. asList() , the list is immutable.

Can we make list immutable class in Java?

In Java, use of() with Set, Map or List to create an Immutable List. Please Note: The programs below are of Java 9. Hence you would need a Java 9 compiler to run them. an ImmutableList can be created from an existing List or both.


1 Answers

in all honesty, that's as best as it gets, but another variant would be:

someDTO.getImmutableList().stream().collect(toCollection(ArrayList::new));
like image 192
Ousmane D. Avatar answered Sep 28 '22 21:09

Ousmane D.