How to convert a Set to Stream in Java

Hello programmers, in this tutorial you will learn how to convert a Set to Stream in Java. In this tutorial, we are going to add some integers in a HashSet and then convert those integers in Stream. Stream basically returns a stream from a collection.

Set: Set is a popular interface that extends the collection framework.

Now let me tell you what is Stream in brief.

Stream: The Stream API is available from Java 8.  A stream is a sequence of objects that supports various methods that can be pipelined to produce the desired result.

Java Program to convert Set to Stream

To write a Java program to convert Set to Stream you need to implement these following steps below:-

  • First, you need to import to packages “import java.util.*;” and “import java.util.stream.Stream;”.
  • Now you have to write the main method in a class named SetToStream.
  • In this main method first, you need to create a new Set of HashSet of type integers and name the object as set1.
  Set<Integer> set1 = new HashSet<>();
  • Now, you need to add integer values to the HashSet using the “.add” method that will help in storing the integer values in the HashSet.
  • Now you need to print the HashSet object. By typing a print statement.
  • Here, after printing the set1 integers now, you have to create an object of the Stream of type integers and pass set1 integers values into the stream by using the “.stream()” method (this will take the input and channels the desired output).
 Stream<Integer> stream1 = set1.stream();
  • Now after converting the integer values in the Stream, you just need to print the elements of Stream using a forEach loop in which you need to use the lambda expression to traverse through every element of Stream and print them.
 stream1.forEach(i->System.out.print(i+" "));

Java Code:

Now it’s time to write our code. Below is our code for this specific task:

import java.util.*; 
import java.util.stream.Stream; 
  
public class SetToStream { 

    public static void main(String[] args) { 
     
    Set<Integer> set1 = new HashSet<>(); 

    set1.add(12); 
    set1.add(18); 
    set1.add(24); 
    set1.add(36); 
    set1.add(48); 
    set1.add(50); 

    System.out.println(set1);
    
    Stream<Integer> stream1 = set1.stream(); 
    System.out.println("\nAfter converting Set values into Stream values\n");
    stream1.forEach(i->System.out.print(i+" ")); 
      
    } 
}

OUTPUT:

[48, 18, 50, 36, 24, 12]

After converting Set values into Stream values

48 18 50 36 24 12

Also, read:

Leave a Reply