Converting List<Integer> to List<String>

ChrisThomas123 picture ChrisThomas123 · Aug 20, 2008 · Viewed 196.7k times · Source

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?

Answer

Ben Lings picture Ben Lings · Aug 4, 2009

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.