The world’s simplest Java streams cheat sheet with code examples.

Introduction

This is a very simple list of examples for Java streams to help when you forget the syntax 😉.

Running The Code

You can download and run the source code as follows.

git clone https://github.com/johndobie/playground.git
mvn clean test

Intermediate Operations

Definitions

Stream<Integer> integerStream = Stream.of(1,2,3,4,5,6,7,8,9);

private Function<Integer, Integer> triple = (value) -> value * 3;
private Predicate<Integer> isGreaterThanFive() { return i -> (i > 5); }

Map

@Test
void testMap() {
    Stream<Integer> mappedStream = integerStream.map(triple);
    assertThat(mappedStream).containsExactly(3,6,9,12,15,18,21,24,27);
}

FlatMap

@Test
void testFlatMap() {
    List<String> names = Arrays.asList("john", "emma");
    List<Character> characterList = names.stream().flatMap(x -> x.chars().mapToObj(i -> (char) i)).collect(Collectors.toList());
    assertThat(characterList).containsExactly('j', 'o', 'h', 'n', 'e', 'm', 'm', 'a');
}

Filter

@Test
void testFilter() {
    List<Integer> integerList = integerStream.filter(isGreaterThanFive()).collect(Collectors.toList());
    assertThat(integerList .size()).isEqualTo(4);
    assertThat(integerList ).contains(6,7,8,9);
}

Peek

@Test
void testPeek() {
    List<Integer> integerList = integerStream.peek(System.out::println)
                                             .map(triple)
                                             .peek(System.out::println)
                                             .collect(Collectors.toList());
}

Limit

@Test
void testLimit() {
    Stream<Integer> limitStream = integerStream.limit(5);
    assertThat(limitStream).containsExactly(1,2,3,4,5);
}

Skip

@Test
void testSkip() {
    Stream<Integer> skipStream = integerStream.skip(5);
    assertThat(skipStream).contains(6,7,8,9);
}

Distinct

@Test
void testDistinct() {
    Stream<Integer> duplicatesStream = Stream.of(1,1,2,2,3,3,3,4);
    List<Integer> distinctList = duplicatesStream.distinct().collect(Collectors.toList());
    assertThat(distinctList).containsExactly(1, 2,  3, 4);
}

Sorted

@Test
void testSorted() {
    Stream<Integer> unsortedStream = Stream.of(5,7,0,2,8,0,4);
    List<Integer> sortedList = unsortedStream.sorted().collect(Collectors.toList());
    assertThat(sortedList).isSorted();
}

Terminating Operations

Definitions

private Stream<Integer> integerStream = Stream.of(1,2,3,4,5,6,7,8,9);

private Predicate<Integer> isGreaterThanFive() { return i -> (i > 5); }

private Function<Integer, Integer> triple = (value) -> value * 3;
private Function<Integer, Integer> plusFive = (value) -> value + 5;
private Function<Integer, Integer> triplePlusFive = triple.andThen(plusFive);

Find Any

@Test
void testFindAny() {
    Optional<Integer> optInt = integerStream.filter(isGreaterThanFive()).findAny();
    assertThat(optInt.get()).isEqualTo(6);
}

All Match

@Test
void testAllMatch() {
    boolean areAllGreaterThanFive = integerStream.allMatch(isGreaterThanFive());
    assertThat(areAllGreaterThanFive).isFalse();
}

Non Match

@Test
void testNoneMatch() {
    boolean areAllGreaterThanFive = integerStream.noneMatch(isGreaterThanFive());
    assertThat(areAllGreaterThanFive).isFalse();
}

Any Match

@Test
void testAnyMatch() {
    boolean areAllGreaterThanFive = integerStream.anyMatch(isGreaterThanFive());
    assertThat(areAllGreaterThanFive).isTrue();
}

Count

@Test
void testCount() {
    long count = integerStream.count();
    assertThat(count).isEqualTo(9);
}

Min With General Comparator

@Test
void testMinWithGeneralComparator() {
    Optional<Integer> optMin = integerStream.min(Comparator.naturalOrder());
    assertThat(optMin.get()).isEqualTo(1);
}

Min With Int Comparator

@Test
void testMinWithIntegerComparator() {
    Optional<Integer> optMin = integerStream.min(Integer::compare);
    assertThat(optMin.get()).isEqualTo(1);
}

Max With Integer Comparator

@Test
void testMaxWithIntegerComparator() {
    Optional<Integer> optMax = integerStream.max(Integer::compare);
    assertThat(optMax.get()).isEqualTo(9);
}

Collect

@Test
void testCollect() {
    List<Integer> integerList = integerStream.collect(Collectors.toList());
    assertThat(integerList).containsExactly(1,2,3,4,5,6,7,8,9);
}

For Each

@Test
void testForEach() {
    List<Integer> tripledIntegerList = integerStream.map(triple).collect(Collectors.toList());
    assertThat(tripledIntegerList).containsExactly(3,6,9,12,15,18,21,24,27);
}

Reduce

@Test
void testReduce() {
    Optional<Integer> sum = integerStream.reduce(Integer::sum);
    assertThat(sum.get()).isEqualTo(45);
}

References.

https://www.oracle.com/technical-resources/articles/java/ma14-java-se-8-streams.html

https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html

Other Blogs You May Like

https://johndobie.com/blog/chatgpt-with-java/

https://johndobie.com/blog/feature-flags-in-java-spring/