Java Streams Cheat Sheet

Introduction to Streams



  • Streams
    • A sequence of elements supporting sequential and parallel aggregate operations.
    • Streams do not store data, they operate on the source of data.
    • Streams are lazy and only execute when a terminal operation is invoked.
  • Stream Operations
    • Intermediate Operations: Transform a stream into another stream. Lazy and only executed when a terminal operation is invoked.
    • Examples: filter(), map(), flatMap(), distinct(), sorted(), limit(), skip().
    • Terminal Operations: Trigger the stream processing and return a result.
    • Examples: forEach(), collect(), reduce(), count(), anyMatch(), noneMatch(), allMatch(), findFirst(), findAny().

Creating Streams



Java
Copy
// From a Collection
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();

// From an Array
String[] array = {"a", "b", "c"};
Stream<String> stream = Arrays.stream(array);

// From Values
Stream<String> stream = Stream.of("a", "b", "c");

// From a File
Stream<String> stream = Files.lines(Paths.get("file.txt"));

// Infinite Streams
Stream<Integer> stream = Stream.iterate(0, n -> n + 1);
Stream<Double> randoms = Stream.generate(Math::random);

Common Intermediate Operations



Java
Copy
// Filters elements based on a condition.
Stream<String> filtered = stream.filter(s -> s.startsWith("a"));

// Transforms each element using the provided function.
Stream<Integer> lengths = stream.map(String::length);

// Flattens the resulting streams into a single stream.
Stream<String> flatMapped = stream.flatMap(s -> Stream.of(s.split(" ")));

// Removes duplicate elements.
Stream<String> distinct = stream.distinct();

// Sorts the elements of the stream.
Stream<String> sorted = stream.sorted();

// Sorts elements using a custom comparator.
Stream<String> sorted = stream.sorted(Comparator.reverseOrder());

// Truncates the stream to contain no more than n elements.
Stream<String> limited = stream.limit(2);

// Skips the first n elements.
Stream<String> skipped = stream.skip(2);

// Performs an action for each element of the stream and returns the same stream.
Stream<String> peeked = stream.peek(System.out::println);

Common Terminal Operations



Java
Copy
// Performs an action for each element.
stream.forEach(System.out::println);

// Transforms the elements into a collection.
List<String> list = stream.collect(Collectors.toList());

// Returns an array containing the elements of the stream.
Object[] array = stream.toArray();

// Combines the elements of the stream into a single value.
Optional<String> reduced = stream.reduce((s1, s2) -> s1 + s2);

// Returns the count of elements in the stream.
long count = stream.count();

// Returns true if any elements match the predicate.
boolean hasMatch = stream.anyMatch(s -> s.startsWith("a"));

// Returns true if all elements match the predicate.
boolean allMatch = stream.allMatch(s -> s.startsWith("a"));

// Returns true if no elements match the predicate.
boolean noneMatch = stream.noneMatch(s -> s.startsWith("a"));

// Returns any element of the stream.
Optional<String> any = stream.findAny();

// Returns the minimum element according to the provided comparator.
Optional<String> min = stream.min(Comparator.naturalOrder());

// Returns the maximum element according to the provided comparator.
Optional<String> max = stream.max(Comparator.naturalOrder());

Collectors



Java
Copy
// Collects the elements into a List.
List<String> list = stream.collect(Collectors.toList());

// Collects the elements into a Set.
Set<String> set = stream.collect(Collectors.toSet());

// Collects the elements into a Map.
Map<String, Integer> map = stream.collect(Collectors.toMap(s -> s, String::length));

// Joins the elements into a single String.
String joined = stream.collect(Collectors.joining(", "));

// Groups the elements by a classifier function.
Map<Integer, List<String>> grouped = stream.collect(Collectors.groupingBy(String::length));

// Partitions the elements into two groups based on a predicate.
Map<Boolean, List<String>> partitioned = stream.collect(Collectors.partitioningBy(s -> s.startsWith("a")));

// Counts the number of elements.
long count = stream.collect(Collectors.counting());

// Summarizes the elements as an IntSummaryStatistics.
IntSummaryStatistics stats = stream.collect(Collectors.summarizingInt(String::length));

Parallel Streams



Java
Copy
// Creating a Parallel Stream
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> parallelStream = list.parallelStream();

// Converting a Sequential Stream to Parallel
Stream<String> parallelStream = stream.parallel();

// Converting a Parallel Stream to Sequential
Stream<String> sequentialStream = parallelStream.sequential();

Stream Examples



Filtering and Mapping


Java
Copy
List<String> result = list.stream()
    .filter(s -> s.startsWith("a"))
    .map(String::toUpperCase)
    .collect(Collectors.toList());

Finding the First Element


Java
Copy
Optional<String> first = list.stream()
    .filter(s -> s.startsWith("b"))
    .findFirst();

Collecting to a Map


Java
Copy
Map<String, Integer> map = list.stream()
    .collect(Collectors.toMap(Function.identity(), String::length));

Grouping and Counting


Java
Copy
Map<Integer, Long> groupedAndCounted = list.stream()
    .collect(Collectors.groupingBy(String::length, Collectors.counting()));

Summarizing Statistics


Java
Copy
IntSummaryStatistics stats = list.stream()
    .collect(Collectors.summarizingInt(String::length));