- Trending Categories
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
Conversion of Stream To Set in Javan
We can convert a stream to set using the following ways.
Using stream.collect() with Collectors.toSet() method - Stream collect() method iterates its elements and stores them in a collection.collect(Collector.toSet()) method.
Using set.add() method - Iterate stream using forEach and then add each element to the set.
Example
import java.util.*; import java.util.stream.Stream; import java.util.stream.Collectors; public class Tester { public static void main(String[] args) { Stream<String> stream = Stream.of("a","b","c","d"); // Method 1 Set<String> set = stream.collect(Collectors.toSet()); set.forEach(data -> System.out.print(data + " ")); Stream<String> stream1 = Stream.of("a","b","c","d"); System.out.println(); //Method 2 Set<String> set1 = new HashSet<>(); stream1.forEach(set1::add); set1.forEach(data -> System.out.print(data + " ")); } }
Output
a b c d a b c d
- Related Articles
- Conversion of Set To Stream in Java\n
- Convert Stream to Set in Java
- Program to convert a Set to Stream in Java using Generics
- Array To Stream in Java
- Conversion of Java Maps to List
- Stream In Java
- Character Stream vs Byte Stream in Java\n
- Stream sorted() in Java
- Conversion of Array To ArrayList in Java\n\n
- Narrowing Conversion in Java
- Java Stream Collectors toCollection() in Java
- Convert an Iterator to Stream in Java
- Convert an Iterable to Stream in Java
- How to convert Stream to TreeSet in Java?
- Program to convert List to Stream in Java

Advertisements