Java Streams Terminal Operations Explained with Examples
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...