Posts

Showing posts with the label Java Streams

Java Streams Collector Operations Explained with Examples

Image
Collectors are the workhorses of Stream terminal aggregation in Java 8. They let you join strings, group and partition data, build specific collection types, and compute statistics — all in a fluent, readable style. 1) Collectors.joining() — Concatenate elements Concatenate stream elements into a single string with optional delimiter, prefix, and suffix. List<String> words = Arrays.asList("apple", "banana", "cherry"); String joined = words.stream() .collect(Collectors.joining(", ", "[", "]")); System.out.println(joined); // [apple, banana, cherry] 2) Collectors.groupingBy() — Group by classifier Group elements based on a key extractor. Default downstream is toList() . List<Person> people = Arrays.asList( new Person("John", "New York"), new Person("Wick", "London"), new Person("Smith", "New York") ); Map...

Java Streams Terminal Operations Explained with Examples

Image
In our previous post, we explored intermediate operations in Java Streams. Now, let’s move to terminal operations . These are the final operations that produce a result (like a value, collection, or side-effect) and terminate the stream pipeline. 1. forEach() The forEach() method is used to perform an action for each element of the stream. List<String> words = Arrays.asList("apple", "banana", "cherry"); words.forEach(word -> System.out.println("item is " + word)); 2. collect() The collect() method gathers the elements of a stream into a collection (like a List, Set, or Map). List<Integer> nums = Arrays.asList(1,1,2,2,2,3,4,5,5,5,6); Set<Integer> res = nums.stream().collect(Collectors.toSet()); System.out.println(res); 3. reduce() The reduce() method performs a reduction on the elements of the stream using an accumulation function. List<Integer> nums = Arrays.asList(1,2,3,4,5); Optional<Integer...