- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to convert a Set to Stream in Java using Generics
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
Advertisements