Program to convert a Set to Stream in Java using Generics

Java 8Object Oriented ProgrammingProgramming

Let’s say the following is our Set −

Set<Integer> set = new HashSet<>(Arrays.asList(15, 40, 60, 90, 120, 150, 200));

Now, create a method to convert the above set to stream.

Stream<Integer>streamOfInteger = convertSet(set);

The method −

private static <T> Stream<T> convertSet(Set<T> set) {
   return set.stream();
}

Example

Following is the program to convert a Set to Stream in Java using Generics −

import java.util.*;
import java.util.stream.*;
import java.util.function.*;
public class Demo {
   private static <T> Stream<T> convertSet(Set<T> set) {
      return set.stream();
   }
   public static void main(String args[]) {
      Set<Integer> set = new HashSet<>(Arrays.asList(15, 40, 60, 90, 120, 150, 200));
      System.out.println("Set = " + set);
      Stream<Integer>streamOfInteger = convertSet(set);
      System.out.println("Stream (Set to Stream) = "+ Arrays.toString(streamOfInteger.toArray()));
   }
}

Output

Set = [150, 40, 120, 200, 90, 60, 15]
Stream (Set to Stream) = [150, 40, 120, 200, 90, 60, 15
raja
Published on 25-Sep-2019 11:12:06
Advertisements