Java program to convert set of integer to set of string

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:

  1. Get the set of integers.
  2. Convert Set of Integer to Stream of Integer. This is done using Set.stream().
  3. Convert Stream of Integer to Stream of String. This is done using Stream.map().
  4. Collect Stream of String into Set of String. This is done using Collectors.toSet().
  5. Return/Print the set of String.

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);
	}
}

 

Submit Your Programming Assignment Details