- 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
Collectors toCollection() method in Java 8
The toCollection() method of the Collectors class in Java returns a Collector that accumulates the input elements into a new Collection in encounter order.
The syntax is as follows
static <T,C extends Collection<T>> Collector<T,?,C> toCollection(Supplier<C> collectionFactory)
Here, the parameter
- T - Type of the input elements
- C - Type of the resulting Collection
- Supplier: A supplier of results
- collectionFactory - Supplier that returns a new, empty Collection of the appropriate type
To work with Collectors class in Java, import the following package
import java.util.stream.Collectors;
The following is an example to implement toCollection() method in Java
Example
import java.util.Collection; import java.util.TreeSet; import java.util.stream.Collectors; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { Stream<String> stream = Stream.of("20", "50", "80", "100", "130", "150", "200"); Collection<String> collection = stream.collect(Collectors.toCollection(TreeSet::new)); System.out.println("Collection = "+collection); } }
Output
Collection = [100, 130, 150, 20, 200, 50, 80]
- Related Articles
- Java Stream Collectors toCollection() in Java
- Collectors toSet() method in Java 8
- Collectors averagingLong () method in Java 8
- Collectors averagingDouble() method in Java 8
- Collectors counting() method in Java 8
- Collectors averagingInt() method in Java 8
- Collectors maxBy() method in Java 8
- Collectors minBy() method in Java 8
- Collectors collectingAndThen() method in Java 8
- Collectors partitioningBy() method in Java 8
- Collectors toList() method in Java 8\n
- Collectors.joining() method in Java 8
- How to create IntSummaryStatistics from Collectors in Java?
- StringJoiner add() method in Java 8
- StringJoiner setEmptyValue() method in Java 8

Advertisements