- 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
Java Stream Collectors toCollection() in Java
The to Collection() 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, T - is the type of the input elements, C is the Type of the resulting Collection, Supplier is the supplier of results, and collection factory is the Supplier that returns a new, empty Collection of the appropriate type
Example
Let us now see an 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("25", "10", "15", "20", "25"); Collection<String> collection = stream.collect(Collectors.toCollection(TreeSet::new)); System.out.println("Collection = "+collection); } }
Output
Collection = [10, 15, 20, 25]
Example
Let us see another 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("Jack", "Tom", "Brad", "Tim", "Kevin", "Bradley", "Ryan"); Collection<String> collection = stream.collect(Collectors.toCollection(TreeSet::new)); System.out.println("Collection = "+collection); } }
Output
Collection = [Brad, Bradley, Jack, Kevin, Ryan, Tim, Tom]
- Related Articles
- Collectors toCollection() method in Java 8
- Collectors toSet() method in Java 8
- Collectors averagingLong () method in Java 8
- Collectors averagingDouble() method in Java 8
- Collectors toList() 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
- Stream In Java
- Character Stream vs Byte Stream in Java
- Stream sorted() in Java
- How to create IntSummaryStatistics from Collectors in Java?

Advertisements