Java Stream API methods: filtering, mapping, sorting, matching, peeking, reducing, collecting, and more.

#Java #java8 1) Intermediate operation. Stream API methods in Java 1. Filtering & Slicing filter(Predicate) – Keeps only elements matching a condition. list.stream().filter(n -> n % 2 == 0).collect(Collectors.toList()); distinct() – Removes duplicates. limit(long maxSize) – Limits the stream to first n elements. skip(long n) – Skips first n elements. --- 2. Mapping & Transforming map(Function) – Transforms each element. list.stream().map(String::toUpperCase).collect(Collectors.toList()); mapToInt, mapToDouble, mapToLong – Maps to primitive streams. flatMap(Function) – Flattens nested structures. listOfLists.stream().flatMap(List::stream).collect(Collectors.toList()); --- 3. Sorting sorted() – Sorts in natural order. list.stream().sorted().collect(Collectors.toList()); sorted(Comparator) – Sorts with custom comparator. list.stream().sorted((a, b) -> b - a).collect(Collectors.toList()); --- 4. Matching & Finding anyMatch(Predicate) – True if any element matches. allMatch(Predicate) – True if all elements match. noneMatch(Predicate) – True if no element matches. findFirst() – Returns first element (optional). findAny() – Returns any element (optional, useful in parallel streams). --- 5. Peeking & Iterating peek(Consumer) – Performs an action on each element (mostly for debugging). list.stream().peek(System.out::println).collect(Collectors.toList()); forEach(Consumer) – Terminal operation to process elements. --- 6. Reducing & Collecting reduce(BinaryOperator) – Combines elements into one. int sum = list.stream().reduce(0, Integer::sum); collect(Collectors.toList()) – Converts stream to list. collect(Collectors.toSet()) – Converts stream to set. collect(Collectors.joining(", ")) – Concatenates strings. collect(Collectors.groupingBy(Function)) – Groups elements by a key. collect(Collectors.partitioningBy(Predicate)) – Splits stream into two groups. --- 7. Other Useful Methods count() – Returns number of elements. min(Comparator) / max(Comparator) – Finds min/max element. toArray() – Converts stream to array. --- ✅ Tips for Intermediate Usage Combine methods for complex queries: list.stream() .filter(n -> n % 2 == 0) .sorted() .map(n -> n * 2) .collect(Collectors.toList()); Use parallelStream() for large datasets. Use peek() for debugging pipelines without altering the stream.

To view or add a comment, sign in

Explore content categories