Java Set is part of the java.util package and extends the java.util.Collection interface. It does not allow repeated elements, and can only hold one empty element at most.
Stream is a series of objects that support various methods that can be pipelined to produce the desired results. The Java 8 Stream API can be used to convert Set to Set.
Algorithm:
Program 1: Using direct conversion.
// Java Program to convert // Set to Set in Java 8 import java.util.*; import java.util.stream.*; class GFG { public static void main(String args[]) { // Create a set of integers Set setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println("Set of Integer: " + setOfInteger); // Convert Set of integers to set of String Set setOfString = setOfInteger.stream() .map(String::valueOf) .collect(Collectors.toSet()); // Print the set of String 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 Program to convert // Set to Set in Java 8 import java.util.*; import java.util.stream.*; import java.util.function.Function; class GFG { // Generic function to convert Set of // Integer to Set of String public static <T, U> Set convertIntSetToStringSet(Set setOfInteger, Function<T, U> function) { return setOfInteger.stream() .map(function) .collect(Collectors.toSet()); } public static void main(String args[]) { // Create a set of integers Set setOfInteger = new HashSet<>( Arrays.asList(1, 2, 3, 4, 5)); // Print the set of Integer System.out.println("Set of Integer: " + setOfInteger); // Convert Set of integers to set of String Set setOfString = convertIntSetToStringSet( setOfInteger, String::valueOf); // Print the set of String System.out.println("Set of String: " + setOfString); } }
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.