Java Stream API Cheat Sheet

Introduction

Java's Stream API, introduced in Java 8, provides a powerful and efficient way to process sequences of elements. Streams can perform operations like filtering, mapping, and reducing on collections, making it easier to work with large datasets and improve code readability. This cheat sheet provides a quick reference to the most commonly used Stream operations, along with examples and explanations.

Java Stream Operations Cheat Sheet

Operation Description
stream() Creates a sequential stream from a collection.
parallelStream() Creates a parallel stream from a collection.
filter(Predicate<T> predicate) Filters elements based on a predicate.
map(Function<T, R> mapper) Transforms elements using a given function.
flatMap(Function<T, Stream<R>>) Transforms elements into streams and then flattens them into a single stream.
distinct() Removes duplicate elements from the stream.
sorted() Sorts the elements in natural order.
sorted(Comparator<T> comparator) Sorts the elements using a provided comparator.
limit(long maxSize) Truncates the stream to contain no more than the specified number of elements.
skip(long n) Skips the first n elements of the stream.
forEach(Consumer<T> action) Performs an action for each element of the stream.
collect(Collector<T, A, R> collector) Collects the elements of the stream into a collection.
reduce(BinaryOperator<T> accumulator) Performs a reduction on the elements using an associative accumulation function.
reduce(T identity, BinaryOperator<T> accumulator) Performs a reduction on the elements with an initial value.
toArray() Returns an array containing the elements of the stream.
anyMatch(Predicate<T> predicate) Returns true if any elements match the provided predicate.
allMatch(Predicate<T> predicate) Returns true if all elements match the provided predicate.
noneMatch(Predicate<T> predicate) Returns true if no elements match the provided predicate.
findFirst() Returns the first element of the stream, if present.
findAny() Returns any element of the stream, useful in parallel streams.
count() Returns the count of elements in the stream.
max(Comparator<T> comparator) Returns the maximum element of the stream according to the provided comparator.
min(Comparator<T> comparator) Returns the minimum element of the stream according to the provided comparator.
peek(Consumer<T> action) Performs the provided action on each element of the stream and returns a new stream with the same elements.
toArray(IntFunction<A[]> generator) Returns an array containing the elements of the stream using the provided generator function.
mapToInt(ToIntFunction<T> mapper) Returns an IntStream consisting of the results of applying the given function to the elements of this stream.
mapToDouble(ToDoubleFunction<T> mapper) Returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.
mapToLong(ToLongFunction<T> mapper) Returns a LongStream consisting of the results of applying the given function to the elements of this stream.
boxed() Converts a primitive stream (IntStream, LongStream, DoubleStream) to a Stream of the corresponding wrapper type.
flatMapToInt(Function<T, IntStream> mapper) Returns an IntStream consisting of the results of replacing each element of this stream with the contents of a mapped IntStream produced by applying the provided mapping function.
flatMapToDouble(Function<T, DoubleStream> mapper) Returns a DoubleStream consisting of the results of replacing each element of this stream with the contents of a mapped DoubleStream produced by applying the provided mapping function.
flatMapToLong(Function<T, LongStream> mapper) Returns a LongStream consisting of the results of replacing each element of this stream with the contents of a mapped LongStream produced by applying the provided mapping function.

Explanation and Examples of Java Stream Operations

stream()

Creates a sequential stream from a collection.
Example:

List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();

Explanation: This method creates a sequential stream from the list of strings.

parallelStream()

Creates a parallel stream from a collection.
Example:

List<String> list = Arrays.asList("a", "b", "c");
Stream<String> parallelStream = list.parallelStream();

Explanation: This method creates a parallel stream from the list of strings.

filter(Predicate<T> predicate)

Filters elements based on a predicate.
Example:

List<String> list = Arrays.asList("apple", "banana", "cherry");
list.stream().filter(s -> s.startsWith("a")).forEach(System.out::println); // apple

Explanation: This method filters the stream to include only elements that start with "a".

map(Function<T, R> mapper)

Transforms elements using a given function.
Example:

List<String> list = Arrays.asList("apple", "banana", "cherry");
list.stream().map(String::toUpperCase).forEach(System.out::println); // APPLE, BANANA, CHERRY

Explanation: This method transforms each element in the stream to its uppercase form.

flatMap(Function<T, Stream<R>> mapper)

Transforms elements into streams and then flattens them into a single stream.
Example:

List<List<String>> list = Arrays.asList(
    Arrays.asList("a", "b"),
    Arrays.asList("c", "d")
);
list.stream().flatMap(Collection::stream).forEach(System.out::println); // a, b, c, d

Explanation: This method flattens the nested lists into a single stream of elements.

distinct()

Removes duplicate elements from the stream.
Example:

List<String> list = Arrays.asList("apple", "banana", "apple");
list.stream().distinct().forEach(System.out::println); // apple, banana

Explanation: This method removes duplicate elements from the stream.

sorted()

Sorts the elements in natural order.
Example:

List<String> list = Arrays.asList("banana", "apple", "cherry");
list.stream().sorted().forEach(System.out::println); // apple, banana, cherry

Explanation: This method sorts the elements in natural order.

sorted(Comparator<T> comparator)

Sorts the elements using a provided comparator.
Example:

List<String> list = Arrays.asList("banana", "apple", "cherry");
list.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println); // cherry, banana, apple

Explanation: This method sorts the elements in reverse order using a comparator.

limit(long maxSize)

Truncates the stream to contain no more than the specified number of elements.
Example:

List<String> list = Arrays.asList("a", "b", "c", "d");
list.stream().limit(2).forEach(System.out::println); // a, b

Explanation: This method limits the stream to the first 2 elements.

skip(long n)

Skips the first n elements of the stream.
Example:

List<String> list = Arrays.asList("a", "b", "c", "d");
list.stream().skip(2).forEach(System.out::println); // c, d

Explanation: This method skips the first 2 elements of the stream.

forEach(Consumer<T> action)

Performs an action for each element of the stream.
Example:

List<String> list = Arrays.asList("a", "b", "c");
list.stream().forEach(System.out::println); // a, b, c

Explanation: This method performs the specified action for each element of the stream.

collect(Collector<T, A, R> collector)

Collects the elements of the stream into a collection.
Example:

List<String> list = Arrays.asList("a", "b", "c");
List<String> result = list.stream().collect(Collectors.toList());

Explanation: This method collects the elements of the stream into a list.

reduce(BinaryOperator<T> accumulator)

Performs a reduction on the elements using an associative accumulation function.
Example:

List<Integer> list = Arrays.asList(1, 2, 3, 4);
int sum = list.stream().reduce((a,

 b) -> a + b).orElse(0); // 10

Explanation: This method reduces the elements of the stream to their sum.

reduce(T identity, BinaryOperator<T> accumulator)

Performs a reduction on the elements with an initial value.
Example:

List<Integer> list = Arrays.asList(1, 2, 3, 4);
int sum = list.stream().reduce(0, Integer::sum); // 10

Explanation: This method reduces the elements of the stream to their sum with an initial value of 0.

toArray()

Returns an array containing the elements of the stream.
Example:

List<String> list = Arrays.asList("a", "b", "c");
String[] array = list.stream().toArray(String[]::new);

Explanation: This method converts the stream to an array.

anyMatch(Predicate<T> predicate)

Returns true if any elements match the provided predicate.
Example:

List<String> list = Arrays.asList("a", "b", "c");
boolean result = list.stream().anyMatch(s -> s.equals("a")); // true

Explanation: This method checks if any element of the stream matches the predicate.

allMatch(Predicate<T> predicate)

Returns true if all elements match the provided predicate.
Example:

List<String> list = Arrays.asList("a", "b", "c");
boolean result = list.stream().allMatch(s -> s.length() == 1); // true

Explanation: This method checks if all elements of the stream match the predicate.

noneMatch(Predicate<T> predicate)

Returns true if no elements match the provided predicate.
Example:

List<String> list = Arrays.asList("a", "b", "c");
boolean result = list.stream().noneMatch(s -> s.equals("d")); // true

Explanation: This method checks if no element of the stream matches the predicate.

findFirst()

Returns the first element of the stream, if present.
Example:

List<String> list = Arrays.asList("a", "b", "c");
Optional<String> result = list.stream().findFirst(); // Optional[a]

Explanation: This method retrieves the first element of the stream.

findAny()

Returns any element of the stream, useful in parallel streams.
Example:

List<String> list = Arrays.asList("a", "b", "c");
Optional<String> result = list.parallelStream().findAny(); // Optional[a] or Optional[b] or Optional[c]

Explanation: This method retrieves any element of the stream, which can be particularly useful when working with parallel streams.

count()

Returns the count of elements in the stream.
Example:

List<String> list = Arrays.asList("a", "b", "c");
long count = list.stream().count(); // 3

Explanation: This method counts the number of elements in the stream.

max(Comparator<T> comparator)

Returns the maximum element of the stream according to the provided comparator.
Example:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> max = list.stream().max(Integer::compareTo); // Optional[5]

Explanation: This method finds the maximum element in the stream using the comparator.

min(Comparator<T> comparator)

Returns the minimum element of the stream according to the provided comparator.
Example:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> min = list.stream().min(Integer::compareTo); // Optional[1]

Explanation: This method finds the minimum element in the stream using the comparator.

peek(Consumer<T> action)

Performs the provided action on each element of the stream and returns a new stream with the same elements.
Example:

List<String> list = Arrays.asList("a", "b", "c");
list.stream().peek(System.out::println).collect(Collectors.toList());
// Output:
// a
// b
// c

Explanation: This method allows for performing an action on each element of the stream without modifying the stream content.

toArray(IntFunction<A[]> generator)

Returns an array containing the elements of the stream using the provided generator function.
Example:

List<String> list = Arrays.asList("a", "b", "c");
String[] array = list.stream().toArray(String[]::new); // [a, b, c]

Explanation: This method converts the stream to an array using the provided array generator function.

mapToInt(ToIntFunction<T> mapper)

Returns an IntStream consisting of the results of applying the given function to the elements of this stream.
Example:

List<String> list = Arrays.asList("a", "bb", "ccc");
IntStream intStream = list.stream().mapToInt(String::length);
intStream.forEach(System.out::println); // 1, 2, 3

Explanation: This method transforms the stream of objects into an IntStream of their lengths.

mapToDouble(ToDoubleFunction<T> mapper)

Returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.
Example:

List<String> list = Arrays.asList("1.0", "2.0", "3.0");
DoubleStream doubleStream = list.stream().mapToDouble(Double::parseDouble);
doubleStream.forEach(System.out::println); // 1.0, 2.0, 3.0

Explanation: This method transforms the stream of objects into a DoubleStream of their double values.

mapToLong(ToLongFunction<T> mapper)

Returns a LongStream consisting of the results of applying the given function to the elements of this stream.
Example:

List<String> list = Arrays.asList("1", "2", "3");
LongStream longStream = list.stream().mapToLong(Long::parseLong);
longStream.forEach(System.out::println); // 1, 2, 3

Explanation: This method transforms the stream of objects into a LongStream of their long values.

boxed()

Converts a primitive stream (IntStream, LongStream, DoubleStream) to a Stream of the corresponding wrapper type.
Example:

IntStream intStream = IntStream.range(1, 5);
Stream<Integer> boxedStream = intStream.boxed();
boxedStream.forEach(System.out::println); // 1, 2, 3, 4

Explanation: This method converts an IntStream into a Stream<Integer>.

flatMapToInt(Function<T, IntStream> mapper)

Returns an IntStream consisting of the results of replacing each element of this stream with the contents of a mapped IntStream produced by applying the provided mapping function.
Example:

Stream<String> stream = Stream.of("a", "bb", "ccc");
IntStream intStream = stream.flatMapToInt(s -> IntStream.of(s.length()));
intStream.forEach(System.out::println); // 1, 2, 3

Explanation: This method maps each element of the stream to an IntStream and flattens them into a single IntStream.

flatMapToDouble(Function<T, DoubleStream> mapper)

Returns a DoubleStream consisting of the results of replacing each element of this stream with the contents of a mapped DoubleStream produced by applying the provided mapping function.
Example:

Stream<String> stream = Stream.of("1.0", "2.0", "3.0");
DoubleStream doubleStream = stream.flatMapToDouble(s -> DoubleStream.of(Double.parseDouble(s)));
doubleStream.forEach(System.out::println); // 1.0, 2.0, 3.0

Explanation: This method maps each element of the stream to a DoubleStream and flattens them into a single DoubleStream.

flatMapToLong(Function<T, LongStream> mapper)

Returns a LongStream consisting of the results of replacing each element of this stream with the contents of a mapped LongStream produced by applying the provided mapping function.
Example:

Stream<String> stream = Stream.of("1", "2", "3");
LongStream longStream = stream.flatMapToLong(s -> LongStream.of(Long.parseLong(s)));
longStream.forEach(System.out::println); // 1, 2, 3

Explanation: This method maps each element of the stream to a LongStream and flattens them into a single LongStream.

Conclusion

Java's Stream API provides a versatile and powerful way to process data collections in a functional style. This cheat sheet covers the most commonly used stream operations, making it easier to leverage the full potential of streams for data manipulation and transformation. Keep this guide handy to reference these operations and enhance your coding efficiency. Happy coding!

Comments