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

Java 8Object Oriented ProgrammingProgramming

Let’s say the following is our Set of Integer −

Set<Integer> setInteger = new HashSet<>(Arrays.asList(100, 200, 300, 500, 600, 800, 1000));

Now, let us convert this to Set of String −

Set<String> setStr = setInteger.stream().map(String::valueOf).collect(Collectors.toSet());

Example

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

import java.util.*;
import java.util.stream.*;
import java.util.function.Function;
public class Demo {
   public static void main(String args[]) {
      Set<Integer> setInteger = new HashSet<>(Arrays.asList(100, 200, 300, 500, 600, 800, 1000));
      System.out.println("Set = " + setInteger);
      Set<String> setStr = setInteger.stream().map(String::valueOf).collect(Collectors.toSet());
      System.out.println("New Set (String) = " + setStr);
   }
}

Output

Set = [800, 100, 500, 200, 600, 1000, 300]
New Set (String) = [100, 200, 300, 500, 600, 800, 1000]
raja
Published on 23-Sep-2019 13:58:11
Advertisements