Search code examples
javastringcollectionsinteger

Converting List<Integer> to List<String>


I have a list of integers, List<Integer> and I'd like to convert all the integer objects into Strings, thus finishing up with a new List<String>.

Naturally, I could create a new List<String> and loop through the list calling String.valueOf() for each integer, but I was wondering if there was a better (read: more automatic) way of doing it?


Solution

  • As far as I know, iterate and instantiate is the only way to do this. Something like (for others potential help, since I'm sure you know how to do this):

    List<Integer> oldList = ...
    /* Specify the size of the list up front to prevent resizing. */
    List<String> newList = new ArrayList<>(oldList.size());
    for (Integer myInt : oldList) { 
      newList.add(String.valueOf(myInt)); 
    }