Program to convert set of String to set of Integer in Java

Java 8Object Oriented ProgrammingProgramming

Let’s say the following is our set of string −

Set<String> setStr = new HashSet<>(Arrays.asList("50", "100", "150", "200", "250", "300", "500"));

Now, convert it to set of Integer −

Set<Integer> setInteger = setStr.stream().map(s -> Integer.parseInt(s)).collect(Collectors.toSet());

Example

Following is the program to convert set of String to set of Integer in Java −

import java.util.*;
import java.util.stream.*;
public class Demo {
   public static void main(String args[]) {
      Set<String> setStr = new HashSet<>(Arrays.asList("50", "100", "150", "200", "250", "300", "500"));
      System.out.println("Set (String) = " + setStr);
      Set<Integer> setInteger = setStr.stream().map(s -> Integer.parseInt(s))
         .collect(Collectors.toSet());
      System.out.println("Set (Integer) = " + setInteger);
   }
}

Output

Set (String) = [100, 200, 300, 500, 50, 150, 250]
Set (Integer) = [50, 100, 500, 150, 200, 250, 300]
raja
Published on 23-Sep-2019 14:01:28
Advertisements