Convert List of String to List of Integer in Java

In this post, we will see how to convert List of String to List of Integer in Java. If the value of specified string is negative (string prefixed with ASCII character ‘-‘ ), the sign should be preserved in the resultant integer.


 

1. Java 8

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

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

 
Note – map() operation will throw a NumberFormatException if the string does not contain a parsable integer.

Download   Run Code

Output:

[-1, 2, 3, 4, 5]

The lambda expression used in above program does nothing but calls an existing method. It is recommended to refer to the existing method by name using method references.

For converting a String to an Integer, we can pass any one of below method references 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. The returned list is just a transformed view of the original list and any changes to original list will be reflected in the returned list. The transformation is done one-way, so new items cannot be added in the returned list.

Download   Run Code

Output:

[-1, 2, 3, 4, 5]

This method also throws a NumberFormatException if string does not contain a parsable integer.

 
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:

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz