Search code examples
javalistarraylistoption-type

How to convert Optional<List<Integer>> to Optional<ArrayList<Integer>>


I've tried to do the following, but it doesn't work

Optional<List<Integer>> listOne = someAPI.call()
// convert
Optional<ArrayList<Integer>> listTwo = new ArrayList<>(listOne); // doesn't work
Optional<ArrayList<Integer>> listTwo = Optional.of(new ArrayList(listOne)); // also not working

Note that the first API returns Optional<List>. And I need to send Optional<ArrayList> to another API.


Solution

  • You can convert it like this:

    Optional<ArrayList<Integer>> listTwo = listOne.map(ArrayList::new);