- 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
How to use the collect() method in Stream API in Java 9?
The collect() method in Stream API collects all objects from a stream object and stored in the type of collection. The user has to provide what type of collection the results can be stored. We specify the collection type using the Collectors Enum. There are different types and different operations can be present in the Collectors Enum, but most of the time we can use Collectors.toList(), Collectors.toSet(), and Collectors.toMap().
Syntax
<R, A> R collect(Collector<? super T,A,R> collector)
Example
import java.util.*; import java.util.stream.*; public class StreamCollectMethodTest { public static void main(String args[]) { List<String> list = List.of("a", "b", "c", "d", "e", "f", "g", "h", "i"); List<String> subset1 = list.stream() .takeWhile(s -> !s.equals("e")) .collect(Collectors.toList()); System.out.println(subset1); List<String> subset2 = list.stream() .dropWhile(s -> !s.equals("e")) .collect(Collectors.toList()); System.out.println(subset2); List<Integer> numbers = Stream.iterate(1, i -> i <= 10, i -> i+1) .collect(Collectors.toList()); System.out.println(numbers); } }
Output
[a, b, c, d] [e, f, g, h, i] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Advertisements
To Continue Learning Please Login
Login with Google