Sunday, 8 June 2025

Collectors in java8 streams

 


Java 8’s Collectors class provides a suite of static methods for accumulating elements from a stream into collections, strings, maps, and more.


 Collectors are typically used with the Stream.collect() method, making it easy to process and transform data in a functional style.


Why:


Collectors provide ready-made solutions for common reduction operations, such as collecting stream elements into collections, grouping, partitioning, joining, and summarizing data. They make code concise, readable, and expressive.


When:


Use collectors when you want to gather, transform, group, or summarize data from a stream into a desired result format (e.g., List, Set, Map, or a single value).


Common Collectors and Their Use Cases


1. Collectors.toList()

When: 

When you want to collect stream elements into a List.


Example:

List<String> cities = Arrays.asList("Mumbai", "Delhi", "Bangalore", "Chennai");

List<String> cityList = cities.stream().collect(Collectors.toList());

System.out.println(cityList); // Output: [Mumbai, Delhi, Bangalore, Chennai]




Explanation:

Collects all stream elements into a List in encounter order


2. Collectors.toSet()

When:

When you need a Set (no duplicates) from stream elements.


Example:

List<String> cities = Arrays.asList("Mumbai", "Delhi", "Mumbai", "Bangalore");

Set<String> citySet = cities.stream().collect(Collectors.toSet());

System.out.println(citySet); // Output: [Mumbai, Delhi, Bangalore]


Explanation:

Removes duplicates by collecting elements into a Set



No comments:

Post a Comment