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