Convert List of Integer to List of String in Java

In this post, we will see how to convert List of Integer to List of String in Java.


 

1. Java 8

We can use Java 8 Stream API to convert List<Integer> to List<String>. Below are the complete steps:

  1. Convert List<Integer> to Stream<Integer> using List.stream().
     
  2. Convert Stream<Integer> to Stream<String> using Stream.map().
     
  3. Accumulate Stream<String> into List<String> using Collectors.toList().

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

It is recommended to use method references for referring an existing method instead of a lambda expression. For converting an Integer to a String, we can pass String::valueOf to the map() function.

 

Using Generics –

Below is generic version of above program. It passes the method reference as an parameter to the generic function.

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

2. Using Guava –

 
1. Guava’s Lists class provides transform() method that returns a list which applies specified function to each element of specified list. This transformation happens in such a way that any changes to original list will be reflected in the returned list but no new items can be added in the returned list.

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 
2. We can also transform a list using a Guava’s Iterables.transform(). It returns a view containing the result of applying function to each element of the list.

Download   Run Code

Output:

[1, 2, 3, 4, 5]

Here’s how we can call Iterables.transform() with Java 7 and before:

 
3. Similar to Iterables.transform(), we can also use Collections2.transform() that returns a collection as shown below:

Download   Run Code

Output:

[1, 2, 3, 4, 5]

Here’s how we can call Collections2.transform() with Java 7 and before:

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of