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 1:
Using Google Collections from Guava-Project, you could use the transform
method in the Lists class
import com.google.common.collect.Lists;
import com.google.common.base.Functions
List<Integer> integers = Arrays.asList(1, 2, 3, 4);
List<String> strings = Lists.transform(integers, Functions.toStringFunction());
The List
returned by transform
is a view on the backing list - the transformation will be applied on each access to the transformed list.
Be aware that Functions.toStringFunction()
will throw a NullPointerException
when applied to null, so only use it if you are sure your list will not contain null.
Solution 2:
Solution for Java 8. A bit longer than the Guava one, but at least you don't have to install a library.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
//...
List<Integer> integers = Arrays.asList(1, 2, 3, 4);
List<String> strings = integers.stream().map(Object::toString)
.collect(Collectors.toList());
For Java 11,
List<String> strings = integers.stream().map(Object::toString)
.collect(Collectors.toUnmodifiableList());
Still no map
convenience method, really?