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?
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.
util. Arrays. asList() , the list is immutable.
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.
in all honesty, that's as best as it gets, but another variant would be:
someDTO.getImmutableList().stream().collect(toCollection(ArrayList::new));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With