Skip to content

Java Stream intermediate operations

In Java 8, Stream intermediate operations are operations that transform a Stream into another Stream.^[java8.md] They form a pipeline through which data flows, allowing for lazy and chained processing of data.

Creating a Stream

Before intermediate operations can be applied, a Stream must be created. Common sources include arrays or collections^[java8.md]:

  • From Arrays: Arrays.stream(new int[] {1, 2, 3})^[java8.md]
  • From Collections: Arrays.asList(1, 2, 3).stream()^[java8.md]
  • Static Methods: Stream.of(1, 2, 3)^[java8.md]
  • Concatenation: Stream.concat(s1, s2)^[java8.md]

Core Intermediate Operations

Filtering

  • filter(Predicate): Used to exclude elements from the stream based on a condition^[java8.md].
    nums.stream().filter(x -> x > 2).forEach(System.out::println);
    
  • distinct(): Returns a stream consisting of distinct (unique) elements, removing duplicates^[java8.md].
  • limit(long n): Retains only the first n elements of the stream^[java8.md].

Mapping

  • map(Function): Transforms each element by applying a function to it, creating a new stream of those results^[java8.md].
    words.stream().map(String::toUpperCase).forEach(System.out::println);
    
  • flatMap(Function): Transforms each element into a stream, and then flattens the resulting streams into a single stream^[java8.md]. This is useful for handling collections of collections or one-to-many transformations.

Sorting

  • sorted(): Sorts the elements of the stream according to their natural order^[java8.md].
  • sorted(Comparator): Sorts the elements using a specific Comparator to define the sorting rules^[java8.md].
  • [[Java Stream]]
  • [[Java 8]]
  • [[Functional Interfaces]]
  • [[Lambda expressions]]

Sources

^[java8.md]