Skip to content

Instantly share code, notes, and snippets.

@etexier
Last active May 11, 2024 19:32
Show Gist options
  • Save etexier/212b8da1a3ef09df313b9b435b57fa47 to your computer and use it in GitHub Desktop.
Save etexier/212b8da1a3ef09df313b9b435b57fa47 to your computer and use it in GitHub Desktop.
Cheat sheet on Java streams

Java Streams

Overview

As part of Java 8 new features, lambda expressions are now supported (Project Lambda). See this very easy-to-read article from Brian Goetz State of the Lambda but more importantly focusing more on streams: State of the Lambda: Libraries Edition

Quick ways to create a stream

// From parameters
Stream<String> s = Stream.of("a", "b");

// From arrays
Arrays.stream(myArray)

// From collections
myCollections.stream()

// you also have specialized streams like IntStream, LongStream, DoubleStream, some example below:
IntStream ints = IntStream.range(0, 10_000);
IntStream rdInts = new Random().ints(1000);

Most common methods

  • filter()
  • mapToInt, mapToObj
  • map()
  • collect()
  • findAny(), findFirst(), noneMatch()
  • forEach()
  • distinct()
  • sorted() sorted(Comparator<? super T>)

Differences map() and flatmap()

These functions can be applied to

  • Optional
  • Stream

map()

map() returns a stream consisting of the results of applying the parameter function to the elements of the stream. This can potentially leads to producing output of type Stream<Stream<R>>, which are hard to work with. In such cases, flatmap() can be used (see below).

flatMap()

flatMap(), as it names indicates, flattens the result. Unlike map() which is only performing a transformation on each element of the stream, flatMap() also perform flattening of the inner streams in the stream resulting from the transformation.

Example:

String[] arr = { "map", "flatmap" }; 
Arrays.stream(arr).flatMap(word -> word.chars().mapToObj(o -> (char) o)).forEach(System.out::println);

This prints:

m
a
p
f
l
a
m
a
p

From stream to collection

Example, use: mystream.collect(Collectors.toList()), mystream.collect(Collectors.toCollection(ArrayList::new)

From stream to array

Example, use: mystream.toArray(String[]::new)

Reduction operations

  • reduce(identity, BinaryOperator<T> accumulator)

Example:

String[] myArray = { "Where", "is", "my", "stream", "?" };
String result = Arrays.stream(myArray)
                .reduce("", (a,b) -> a + " " + b);
assert result.equals(" Where is my stream ?");               

Others...

  • sum()
  • average()
  • count()

Parallelization

The motivation behind the stream API was mostly to enable easy parallelization

Use these methods:

  • myStream.parallel()
  • myCollection.parallelStream()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment