- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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]
- Related Articles
- Importance of iterate() method of Stream API in Java 9?\n
- When to use the ofNullable() method of Stream in Java 9?\n
- How can we implement methods of Stream API in Java 9?
- What are the new features added to Stream API in Java 9?
- How to use intermediate stream operations in JShell in Java 9?
- How to use terminal stream operations in JShell in Java 9?
- How to iterate List Using Java Stream API?
- StackWalker API in Java 9?
- How to sort a collection by using Stream API with lambdas in Java?
- How to print all attributes in StackFrame API in Java 9?
- When to use the readAllBytes() method of InputStream in Java 9?
- When to use the readNBytes() method of InputStream in Java 9?
- When to use the delayedExecutor() method of CompletableFuture in Java 9?
- How to get a stream from Optional class in Java 9?
- How to get the parent process of the Process API in Java 9?

Advertisements