This post will discuss how to convert Set of String to Set of Integer in Java 8 and above. If the value of the specified string is negative, the solution should preserve the sign in the resultant integer.

We can use Java 8 Stream to convert Set<String> to Set<Integer>. The following are the complete steps:

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

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

Download  Run Code

 
The lambda expression used in the above program does nothing but calls an existing method. 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)

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

Download  Run Code

 
This is equivalent to:

Download  Run Code

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