
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Java
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
Advertisements