Simplified Stream Method Implementations in Java

Explore simplified implementations of essential Java Stream methods, including map, reduce, and generate. These code snippets offer insights into how these methods might be internally implemented, facilitating a deeper understanding of functional programming paradigms in Java. While these implementations lack the intricacies and optimizations of the official Java Stream API, they serve as educational tools for those seeking to grasp the fundamental concepts behind stream processing in Java.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Predicate;

public class Stream<T> {
    private final List<T> source;

    public Stream(List<T> source) {
        this.source = source;
    }

    public Stream<T> filter(Predicate<T> predicate) {
        List<T> result = new ArrayList<>();
        for (T element : source) {
            if (predicate.test(element)) {
                result.add(element);
            }
        }
        return new Stream<>(result);
    }

    // Other stream operations like map, reduce, etc. could be implemented similarly
}

In this simplified implementation:

  • The Stream class represents a stream of elements of type T.
  • The filter method takes a Predicate as an argument and returns a new Stream containing only the elements for which the predicate returns true.
  • Inside the filter method, we iterate over each element of the source stream (source), apply the predicate to each element using the test method of the Predicate interface, and add the element to the result stream if the predicate returns true.
  • Finally, we return a new Stream containing the filtered elements.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class Stream<T> {
    private final List<T> source;

    public Stream(List<T> source) {
        this.source = source;
    }

    public <R> Stream<R> map(Function<T, R> mapper) {
        List<R> result = new ArrayList<>();
        for (T element : source) {
            result.add(mapper.apply(element));
        }
        return new Stream<>(result);
    }
}
import java.util.List;
import java.util.function.BinaryOperator;

public class Stream<T> {
    private final List<T> source;

    public Stream(List<T> source) {
        this.source = source;
    }

    public T reduce(T identity, BinaryOperator<T> accumulator) {
        T result = identity;
        for (T element : source) {
            result = accumulator.apply(result, element);
        }
        return result;
    }
}

You may also like...