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 String.
- Convert Set of String to Stream of String. This is done using Set.stream().
- Convert Stream of String to Stream of Integer. This is done using Stream.map() and passing Integer.parseInt() method as lambda expression.
- Collect Stream of Integer into Set of Integer. This is done using Collectors.toSet().
- Return/Print the set of String.
Program 1: Using direct conversion.
import java.util.*;
import java.util.stream.*;
class GFG {
public static void main(String args[])
{
Set<String> setOfString = new HashSet<>(
Arrays.asList( "1" , "2" , "3" , "4" , "5" ));
System.out.println( "Set of String: " + setOfString);
Set<Integer> setOfInteger = setOfString.stream()
.map(s -> Integer.parseInt(s))
.collect(Collectors.toSet());
System.out.println( "Set of Integer: " + setOfInteger);
}
}
|
Output:
Set of String: [1, 2, 3, 4, 5]
Set of Integer: [1, 2, 3, 4, 5]
Program 2: Using generic function.
import java.util.*;
import java.util.stream.*;
import java.util.function.Function;
class GFG {
public static <T, U> Set<U>
convertStringSetToIntSet(Set<T> setOfString,
Function<T, U> function)
{
return setOfString.stream()
.map(function)
.collect(Collectors.toSet());
}
public static void main(String args[])
{
Set<String> setOfString = new HashSet<>(
Arrays.asList( "1" , "2" , "3" , "4" , "5" ));
System.out.println( "Set of String: " + setOfString);
Set<Integer> setOfInteger = convertStringSetToIntSet(
setOfString,
Integer::parseInt);
System.out.println( "Set of Integer: " + setOfInteger);
}
}
|
Output:
Set of String: [1, 2, 3, 4, 5]
Set of Integer: [1, 2, 3, 4, 5]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
11 Dec, 2018
Like Article
Save Article