convert Set<Integer> to Set<String> in java-8
we can see how to convert Set of Integer to Set of String in Java 8. Let’s use Java 8 Stream API to convert Set of Integer to Set of String.
We can use Java 8 Stream API to convert Set<Integer> to Set<String>. Below are the complete steps:
- Convert Set<Integer> to Stream<Integer> using Set.stream().
- Convert Stream<Integer> to Stream<String> using Stream.map().
- Accumulate Stream<String> into Set<String> using Collectors.toSet().
import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;
import java.util.stream.Collectors;
class SetUtilities
{
// Program to convert Set of Integer to Set of String
public static void main(String args[])
{
Set<Integer> ints = new HashSet<>(Arrays.asList(11, 22, 33, 44, 55));
Set<String> stritems = ints.stream().map(String::valueOf).collect(Collectors.toSet());
System.out.println(stritems );
}
}
C:\>javac SetUtilities.java
C:\>java SetUtilities
[11, 22, 33, 44, 55]
Here is the generic code of above program. It passes the method reference as an parameter to the generic function.
import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;
import java.util.function.Function;
import java.util.stream.Collectors;
class SetUtilities
{
// Generic function to convert Set of Integer to Set of String
public static <T, U> Set<U> transform(Set<T> set, Function<T, U> function)
{
return set.stream().map(function).collect(Collectors.toSet());
}
// Program to convert Set of Integer to Set of String
public static void main(String args[])
{
Set<Integer> ints = new HashSet<>(Arrays.asList(11, 22, 33, 44, 55));
Set<String> stritems = transform(ints, String::valueOf);
System.out.println(stritems );
}
}
C:\>javac SetUtilities.java
C:\>java SetUtilities
[11, 22, 33, 44, 55]
Recent Comments