Convert Set of String to Set of Integer in Java 8

In this post, we will see how to convert Set of String to Set of Integer in Java 8. If the value of specified string is negative, the sign should be preserved in the resultant integer.


 

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

Download   Run Code

Output:

[-1, 2, -3, 4]

 
The lambda expression used in above program does nothing but calls an existing method. For converting a String to an Integer, we can pass any one of below method references to the map() function –

 
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]

 
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