Primitive Streams

Overview

Cheat Sheet

<!-- Creating Primitive Streams -->
IntStream.of(int...)
IntStream.range(int, int)
IntStream.generate(IntSupplier)
IntStream.iterate(int, IntUnaryOperator)
Random.ints()
Random.ints(int, int)

<!-- Intermediate Operations on Primitive Streams -->
IntStream.flatMapToInt(ToIntFunction)
IntStream.mapToObj(IntFunction)
IntStream.boxed()

<!-- Terminal Operations on Primitive Streams -->
is.toArray();
is.min();
is.max();
is.average();
is.sum();
is.summaryStatistics();

Creating Primitive Streams

Creating Primitive Streams Using [Int | Long | Double]Stream Methods

IntStream.of(int…)

import java.util.stream.IntStream;

class Foo {    
    void foo() {
        IntStream.of(1, 2); // IntStream with values 1, 2
    }
}

IntStream.range(int, int)

import java.util.stream.IntStream;

class Foo {    
    void foo() {
        IntStream.range(1, 6); // IntStream with values 1, 2, 3, 4, 5
    }
}

IntStream.generate(IntSupplier)

import java.util.stream.IntStream;

class Foo {    
    void foo() {
        IntStream.generate(() -> 1); // // An infinite IntStream of 1s
    }
}

IntStream.iterate(int, IntUnaryOperator)

import java.util.stream.IntStream;

class Foo {    
    void foo() {
        IntStream.iterate(1, i -> i * 2); // An infinite IntStream of: 1, 2, 4, 8, 16...
    }
}

Creating Primitive Streams Using the Random class

Random.ints()

import java.util.Random;;

class Foo {
    void foo() {
        final Random random = new Random();
        random.ints();
    }
}

Intermediate Operations on Primitive Streams

FlatMapping to Primitive Type Streams

Stream.flatMapToInt(Function)

import java.util.stream.Stream;
import java.util.stream.IntStream;

class Foo {    
    int foo;
    int bar;
    
    Foo(int foo, int bar){this.foo = foo; this.bar = bar;}

    void foo() {
        Stream<Foo> foo = Stream.of(new Foo(1, 2), new Foo(3, 4));
        foo.flatMapToInt(f -> IntStream.of(f.foo, f.bar)); // IntStream with values: 1, 2, 3, 4
    }
}

Mapping to Generic Stream

IntStream.mapToObj(IntFunction)

import java.util.stream.Stream;
import java.util.stream.IntStream;


class Foo {
    int val;
    
    Foo(int val){this.val = val;}
    
    void foo() {
        IntStream is = IntStream.rangeClosed(1, 2);
        is.mapToObj(i -> new Foo(i)); // A Stream<Foo> with 2 instances: Foo[1] and Foo[2]
        // Another possibility: is.mapToObj(Foo::new);
    }
}

Also see: IntStream.boxed()

Terminal Operations on Primitive Streams


MethodReturn TypeReference Stream Equivalent
toArray()int[]
count()longStream.count()
min()OptionalIntStream.min(Comparator)
max()OptionalIntStream.max(Comparator)
average()OptionalDoubleStream.collect(Collectors.averagingInt(ToIntFunction))
sum()intStream.collect(Collectors.summingInt(ToIntFunction))
summaryStatistics()IntSummaryStatisticsStream.collect(Collectors.summarizingInt(ToIntFunction))
findAny()OptionalIntStream.findAny()
findFirst()OptionalIntStream.findFirst()

🏠