This post will discuss how to convert list of string to list of Integer in Java. If the value of the specified string is negative (string prefixed with ASCII character ‘-‘ ), the solution should preserve the sign in the resultant integer.

1. Using Java 8

We can use Java 8 Stream to convert List<String> to List<Integer>. Following 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 that map() operation will throw a NumberFormatException if the string does not contain a parsable integer.

Download  Run Code

 
This is equivalent to:

Download  Run Code

 
The lambda expression used in the 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 the following method references to the map() method:

Integer::parseInt
Integer::valueOf
Integer::decode
NumberUtils::toInt    // provided by Apache Commons Lang Math class

Using Generics:

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

Download  Run Code

2. Using Guava Library

 
1. Guava’s Lists class provides the transform() method that returns a list that applies a specified method to each element of the specified list. The returned list is just a transformed view of the original list, and any changes to the original list will be reflected in the returned list. The transformation is done one-way, so we cannot add new items to the returned list.

Download Code

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

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

Download Code

 
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 Code

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

That’s all about converting List of String to Integer List in Java.