Java Set is a part of java.util package and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element. A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Java 8 Stream API can be used to convert Set to Set. Algorithm:
- Get the set of integers.
- Convert Set of Integer to Stream of Integer. This is done using Set.stream().
- Convert Stream of Integer to Stream of String. This is done using Stream.map().
- Collect Stream of String into Set of String. This is done using Collectors.toSet().
- Return/Print the set of String.
Program 1: Using direct conversion.
Java
import java.util.*;
import java.util.stream.*;
class GFG {
public static void main(String args[])
{
Set<Integer> setOfInteger = new HashSet<>(
Arrays.asList( 1 , 2 , 3 , 4 , 5 ));
System.out.println("Set of Integer: " + setOfInteger);
Set<String> setOfString = setOfInteger.stream()
.map(String::valueOf)
.collect(Collectors.toSet());
System.out.println("Set of String: " + setOfString);
}
}
|
Output:Set of Integer: [1, 2, 3, 4, 5]
Set of String: [1, 2, 3, 4, 5]
Program 2: Using generic function.
Java
import java.util.*;
import java.util.stream.*;
import java.util.function.Function;
class GFG {
public static <T, U> Set<U>
convertIntSetToStringSet(Set<T> setOfInteger,
Function<T, U> function)
{
return setOfInteger.stream()
.map(function)
.collect(Collectors.toSet());
}
public static void main(String args[])
{
Set<Integer> setOfInteger = new HashSet<>(
Arrays.asList( 1 , 2 , 3 , 4 , 5 ));
System.out.println("Set of Integer: " + setOfInteger);
Set<String> setOfString = convertIntSetToStringSet(
setOfInteger,
String::valueOf);
System.out.println("Set of String: " + setOfString);
}
}
|
Output:Set of Integer: [1, 2, 3, 4, 5]
Set of String: [1, 2, 3, 4, 5]
Method 3 : Naive Approach using toString()
1. Initialize and declare the set of integer values in Hashset.
2. Initialize the HashSet of String object.
3. Iterate the for loop and add the integer values of hashset to string hashset by converting integer to string using toString().
Java
import java.util.*;
class GFG {
public static void main (String[] args) {
Set<Integer> setOfInteger = new HashSet<>(
Arrays.asList( 1 , 2 , 3 , 4 , 5 ));
System.out.println( "Set of Integer: " + setOfInteger);
Set<String> setOfString = new HashSet<>();
for (Integer i:setOfInteger)
{
setOfString.add(i.toString());
}
System.out.println( "Set of String: " + setOfString);
}
}
|
Output :
Set of Integer: [1, 2, 3, 4, 5]
Set of String: [1, 2, 3, 4, 5]