Posts

Showing posts with the label Java 8

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...

Java Streams Intermediate Operations Explained with Examples

Image
The Java Stream API lets you process collections in a fluent, declarative style. In this post, we’ll walk through the most useful intermediate operations with simple examples. Note: Examples below use Java 8 compatible collect(Collectors.toList()) . If you’re on Java 16+, you can replace it with toList() . 1) filter() — Select elements by a condition Keeps only elements that match the predicate. List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10); List<Integer> res = list.stream() .filter(num -> num % 2 != 0) // keep only odd numbers .collect(Collectors.toList()); System.out.println(res); // [1, 3, 5, 7, 9] 2) map() — Transform each element Applies a function to every element and returns a stream of results. List<String> strs = Arrays.asList("rama", "anjaneya", "krishna"); List<String> upper = strs.stream() .map(String::toUpperCase) .collect(Collectors.toList()); System.o...