Code

import java.util.*;import java.util.stream.*;public class StreamOperations {        // Filter elements    public static <T> List<T> filter(List<T> list, Predicate<T> predicate) {        return list.stream()            .filter(predicate)            .collect(Collectors.toList());    }        // Map elements to another type    public static <T, R> List<R> map(List<T> list, Function<T, R> mapper) {        return list.stream()            .map(mapper)            .collect(Collectors.toList());    }        // Reduce to single value    public static <T> Optional<T> reduce(List<T> list, BinaryOperator<T> accumulator) {        return list.stream().reduce(accumulator);    }        // Group by classifier    public static <T, K> Map<K, List<T>> groupBy(List<T> list, Function<T, K> classifier) {        return list.stream()            .collect(Collectors.groupingBy(classifier));    }        // Flat map nested collections    public static <T, R> List<R> flatMap(List<List<T>> nested, Function<List<T>, Stream<R>> mapper) {        return nested.stream()            .flatMap(mapper)            .collect(Collectors.toList());    }        // Distinct elements    public static <T> List<T> distinct(List<T> list) {        return list.stream()            .distinct()            .collect(Collectors.toList());    }        // Sort elements    public static <T> List<T> sorted(List<T> list, Comparator<T> comparator) {        return list.stream()            .sorted(comparator)            .collect(Collectors.toList());    }}
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);// Filter even numbersList<Integer> evens = numbers.stream()    .filter(n -> n % 2 == 0)    .collect(Collectors.toList());// Map to squaresList<Integer> squares = numbers.stream()    .map(n -> n * n)    .collect(Collectors.toList());// Sum all numbersint sum = numbers.stream()    .reduce(0, Integer::sum);// Find maximumOptional<Integer> max = numbers.stream()    .max(Integer::compareTo);// Group by even/oddMap<Boolean, List<Integer>> grouped = numbers.stream()    .collect(Collectors.partitioningBy(n -> n % 2 == 0));// Parallel processingList<Integer> doubled = numbers.parallelStream()    .map(n -> n * 2)    .collect(Collectors.toList());// Chain operationsList<String> result = numbers.stream()    .filter(n -> n > 5)    .map(n -> "Number: " + n)    .sorted()    .collect(Collectors.toList());

Comments

No comments yet. Be the first!