Convert Set of Integer to Set of String in Java 8 and above
This post will discuss how to convert set of Integer to set of string in Java.
We can use Java 8 Stream to convert Set<Integer> to Set<String>. Following are the complete steps:
- Convert
Set<Integer>toStream<Integer>usingSet.stream(). - Convert
Stream<Integer>toStream<String>usingStream.map(). - Accumulate
Stream<String>intoSet<String>usingCollectors.toSet().
The following program demonstrates it:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.Arrays; import java.util.Set; import java.util.HashSet; import java.util.stream.Collectors; class Main { public static void main(String[] args) { Set<Integer> ints = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5)); Set<String> items = ints.stream() .map(String::valueOf) .collect(Collectors.toSet()); System.out.println(items); // [1, 2, 3, 4, 5] } } |
Following is a generic version of the above program. It passes the method reference as a parameter to the generic function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.Arrays; import java.util.Set; import java.util.HashSet; import java.util.function.Function; import java.util.stream.Collectors; class Main { // Generic method to convert `Set<Integer>` to `Set<String>` public static <T, U> Set<U> transform(Set<T> set, Function<T, U> function) { return set.stream() .map(function) .collect(Collectors.toSet()); } public static void main(String[] args) { Set<Integer> ints = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5)); Set<String> items = transform(ints, String::valueOf); System.out.println(items); // [1, 2, 3, 4, 5] } } |
This is equivalent to:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.function.Function; class Main { // Generic method to convert `Set<Integer>` to `Set<String>` public static <T, U> Set<U> transform(Set<T> set, Function<T, U> function) { Set<U> result = new HashSet<>(); for (T t : set) { U u = function.apply(t); result.add(u); } return result; } public static void main(String[] args) { Set<Integer> ints = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5)); Set<String> items = transform(ints, String::valueOf); System.out.println(items); // [1, 2, 3, 4, 5] } } |
That’s all about converting Set of Integer to Set of String in Java 8.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)