Streams

Framework for processing sequences of data in declarative and functional style.

Basically, you can specify an operation and perform it for all items in the collection.

Intermediate Operations

Intermediate operations return a stream.

filter(Predicate)

Filters elements based on a condition.

List<Integer> evens = numbers.stream()
                            .filter(n -> n % 2 == 0)
                            .collect(Collectors.toList());

map(Function)

Transform each element of the stream.

List<String> upperNames = names.stream()
                               .map(String::toUpperCase)
                               .collect(Collectors.toList());

flatMap(Function)

Flattens stream of streams into a single stream.

List<String> allWords = sentences.stream()
                                 .flatMap(sentence -> Arrays.stream(sentence.split(" ")))
                                 .collect(Collectors.toList());

Stream<List<Integer>> nestedStream = Stream.of(List.of(1, 2), List.of(3, 4));
Stream<Integer> flattenedStream = nestedStream.flatMap(List::stream);

distinct()

Removes duplicates.

List<Integer> uniqueNumbers = numbers.stream()
                                     .distinct()
                                     .collect(Collectors.toList());

sorted() and sorted(Comparator)

Sorts by natural order or by Comparator, if passed.

List<String> sortedNames = names.stream()
                                .sorted()
                                .collect(Collectors.toList());
List<Person> sortedByAge = people.stream()
                                 .sorted(Comparator.comparing(Person::getAge))
                                 .collect(Collectors.toList());

peek(Consumer)

Performs an action on each element without altering the stream.

numbers.stream()
       .peek(n -> System.out.println("Processing number: " + n))
       .collect(Collectors.toList());

limit(long n)

Limits the stream to first n elements.

List<Integer> firstThree = numbers.stream()
                                  .limit(3)
                                  .collect(Collectors.toList());

skip(long n)

Skips the first n elements.

List<Integer> withoutFirstTwo = numbers.stream()
                                       .skip(2)
                                       .collect(Collectors.toList());

Terminal Operations

These operations consume the stream and return a result.

forEach(Consumer)

Performs an operation for each element.

names.stream().forEach(System.out::println);

collect(Collector)

Collects the stream into a collection. Instance of Collector can be fetched from Collectors API.

List<String> collectedNames = names.stream().collect(Collectors.toList());

<U> U reduce(U identity, BinaryOperator accumulator)

Reduces stream to a single value.

  • identity value is used as the initial value
  • accumulator function is used to combine all the elements.
int sum = numbers.stream()
                 .reduce(0, Integer::sum);

toArray()

Converts stream into array.

String[] nameArray = names.stream().toArray(String[]::new);

min(Comparator) and max(Comparator)

Optional<Integer> min = numbers.stream()
                               .min(Comparator.naturalOrder());

count()

long count = numbers.stream().count();

anyMatch(Predicate), allMatch(Predicate) and noneMatch(Predicate)

boolean hasEven = numbers.stream()
                         .anyMatch(n -> n % 2 == 0);

findFirst()

Optional<Integer> first = numbers.stream()
                                 .findFirst();

findAny()

Optional<Integer> any = numbers.stream()
                               .findAny();


Introduced in Java 8


Backlinks