I try this but it does not work
Optional<List<Integer>> listOne = someAPI.call()
// convert
Optional<ArrayList<Integer>> listTwo = new ArrayList<>(listOne); // does not work
Optional<ArrayList<Integer>> listTwo = Optional.of(new ArrayList(listOne)); // also not work
Note that this API return Optional and I need to send Optional to another API.
Thank you so much
CodePudding user response:
You can convert it like this:
Optional<ArrayList<Integer>> listTwo = listOne.map(ArrayList::new);
CodePudding user response:
If you start with this:
Optional<List<Integer>> optionalList = getFromSomewhere();
You can convert to Optional<ArrayList<Integer>>
like this:
Optional<ArrayList<Integer>> optionalArrayList
= Optional.of(new ArrayList<>(optionalList.get()));
This is close to what you tried - Optional.of(new ArrayList(listOne))
– but your attempt didn't work because listOne
is type Optional<List<Integer>>
, whereas the constructor to new ArrayList()
takes a Collection. If you call .get()
then you'll get the list out of the Optional, and that works fine for the ArrayList constructor.