Java : Stream with Examples

Stream (Java SE 21 & JDK 21) with Examples.
You will find code examples on most Stream<T> methods.


Summary

A sequence of elements supporting sequential and parallel aggregate operations.

Class diagram

final var list = List.of("y", "z", "b", "x", "a", "c");
System.out.println(list); // [y, z, b, x, a, c]

// Convert elements to uppercase and sort.
final var ret = list.stream()
        .map(str -> str.toUpperCase())
        .sorted()
        .toList();

System.out.println(ret); // [A, B, C, X, Y, Z]
final var stream = Stream.of(1, 2, 2, 3, 3, 3);

final var ret = stream.distinct().toList();
System.out.println(ret); // [1, 2, 3]

Methods

boolean allMatch (Predicate<? super T> predicate)

Returns whether all elements of this stream match the provided predicate.

final var predicate = new Predicate<Character>() {
    @Override
    public boolean test(Character c) {
        // Checks if the character is lowercase.
        return Character.isLowerCase(c);
    }
};

{
    final var stream = Stream.of('a', 'b', 'c', 'd');

    final var ret = stream.allMatch(predicate);
    System.out.println(ret); // true
}
{
    final var stream = Stream.of('a', 'B', 'c', 'D');

    final var ret = stream.allMatch(predicate);
    System.out.println(ret); // false
}

boolean anyMatch (Predicate<? super T> predicate)

Returns whether any elements of this stream match the provided predicate.

final var predicate = new Predicate<Character>() {
    @Override
    public boolean test(Character c) {
        // Checks if the character is lowercase.
        return Character.isLowerCase(c);
    }
};

{
    final var stream = Stream.of('a', 'b', 'c');

    final var ret = stream.anyMatch(predicate);
    System.out.println(ret); // true
}
{
    final var stream = Stream.of('A', 'b', 'c');

    final var ret = stream.anyMatch(predicate);
    System.out.println(ret); // true
}
{
    final var stream = Stream.of('A', 'B', 'C');

    final var ret = stream.anyMatch(predicate);
    System.out.println(ret); // false
}

static <T> Stream.Builder<T> builder ()

Returns a builder for a Stream.

final var builder = Stream.<String>builder();
builder.add("aaa").add("bbb").add("ccc");

final var stream = builder.build();

System.out.println(stream.toList()); // [aaa, bbb, ccc]

<R> R collect (Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner)

Performs a mutable reduction operation on the elements of this stream.

final var supplier = new Supplier<List<String>>() {
    @Override
    public List<String> get() {
        System.out.println("-- supplier --");
        return new ArrayList<>();
    }
};

final var accumulator = new BiConsumer<List<String>, String>() {
    @Override
    public void accept(List<String> list, String value) {
        System.out.println("-- accumulator --");
        System.out.println("  list = " + list);
        System.out.println("  value = " + value);

        list.add(value);
    }
};

final var combiner = new BiConsumer<List<String>, List<String>>() {
    @Override
    public void accept(List<String> list1, List<String> list2) {
        System.out.println("-- combiner --");
        System.out.println("  list1 = " + list1);
        System.out.println("  list2 = " + list2);

        list1.addAll(list2);
    }
};

{
    final var stream = Stream.of("aaa", "bbb", "ccc");

    final var ret = stream.collect(supplier, accumulator, combiner);
    System.out.println("collect = " + ret);

    // Result
    // ↓
    //-- supplier --
    //-- accumulator --
    //  list = []
    //  value = aaa
    //-- accumulator --
    //  list = [aaa]
    //  value = bbb
    //-- accumulator --
    //  list = [aaa, bbb]
    //  value = ccc
    //collect = [aaa, bbb, ccc]
}
{
    final var parallelStream = Stream.of("aaa", "bbb", "ccc").parallel();
    System.out.println(parallelStream.isParallel()); // true

    final var ret = parallelStream.collect(supplier, accumulator, combiner);
    System.out.println("collect = " + ret);

    // Result
    // ↓
    //-- supplier --
    //-- accumulator --
    //  list = []
    //  value = bbb
    //-- supplier --
    //-- accumulator --
    //  list = []
    //  value = ccc
    //-- supplier --
    //-- accumulator --
    //  list = []
    //  value = aaa
    //-- combiner --
    //  list1 = [bbb]
    //  list2 = [ccc]
    //-- combiner --
    //  list1 = [aaa]
    //  list2 = [bbb, ccc]
    //collect = [aaa, bbb, ccc]
}

<R, A> R collect (Collector<? super T,A,R> collector)

Performs a mutable reduction operation on the elements of this stream using a Collector.

final var stream = Stream.of("aaa", "bbb", "ccc");

final Set<String> set = stream.collect(Collectors.toSet());
System.out.println(set); // [aaa, ccc, bbb]
final var stream = Stream.of("X", "Y", "Z");
final Map<String, String> map = stream.collect(Collectors.toMap(
        s -> s + "-key",
        s -> s + "-value"
));

// {X-key=X-value, Z-key=Z-value, Y-key=Y-value}
System.out.println(map);
final var stream = Stream.of("a", "b", "c");

final String str = stream.collect(Collectors.joining("-"));
System.out.println(str); // a-b-c

static <T> Stream<T> concat (Stream<? extends T> a, Stream<? extends T> b)

Creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.

final var stream1 = Stream.of("aaa", "bbb", "ccc");
final var stream2 = Stream.of("XX", "YY", "ZZ");

System.out.println(stream1.isParallel()); // false
System.out.println(stream2.isParallel()); // false

final var concatStream = Stream.concat(stream1, stream2);
System.out.println(concatStream.isParallel()); // false
System.out.println(concatStream.toList()); // [aaa, bbb, ccc, XX, YY, ZZ]
final var stream1 = Stream.of("aaa", "bbb", "ccc").parallel();
final var stream2 = Stream.of("XX", "YY", "ZZ").parallel();

System.out.println(stream1.isParallel()); // true
System.out.println(stream2.isParallel()); // true

final var concatStream = Stream.concat(stream1, stream2);
System.out.println(concatStream.isParallel()); // true
System.out.println(concatStream.toList()); // [aaa, bbb, ccc, XX, YY, ZZ]

long count ()

Returns the count of elements in this stream.

final var stream = Stream.of("a", "b", "c", "d");
System.out.println(stream.count()); // 4
final var stream = Stream.empty();
System.out.println(stream.count()); // 0

Stream<T> distinct ()

Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.

final var stream = Stream.of("aaa", "bbb", "ccc", "bbb", "ccc");

final var ret = stream.distinct().toList();
System.out.println(ret); // [aaa, bbb, ccc]
final var stream = Stream.of(1, 2, 2, 3, 3, 3);

final var ret = stream.distinct().toList();
System.out.println(ret); // [1, 2, 3]

default Stream<T> dropWhile (Predicate<? super T> predicate)

Returns, if this stream is ordered, a stream consisting of the remaining elements of this stream after dropping the longest prefix of elements that match the given predicate.

final var stream = Stream.of("aa", "bb", "cc", "dd", "ee", "ff");

final var predicate = new Predicate<String>() {
    @Override
    public boolean test(String s) {
        return !s.equals("dd");
    }
};

final var ret = stream.dropWhile(predicate).toList();
System.out.println(ret); // [dd, ee, ff]
final var stream = Stream.of(1, 2, 3, 4, 5);

final var ret = stream.dropWhile(v -> v != 3).toList();
System.out.println(ret); // [3, 4, 5]

static <T> Stream<T> empty ()

Returns an empty sequential Stream.

final var stream = Stream.<String>empty();
System.out.println(stream.count()); // 0
final var stream = Stream.<Integer>empty();
final var list = stream.toList();
System.out.println(list); // []

Stream<T> filter (Predicate<? super T> predicate)

Returns a stream consisting of the elements of this stream that match the given predicate.

final var stream = Stream.of('a', 'b', 'C', 'D', 'e');

final var predicate = new Predicate<Character>() {
    @Override
    public boolean test(Character c) {
        // Checks if the character is lowercase.
        return Character.isLowerCase(c);
    }
};

final var ret = stream.filter(predicate).toList();
System.out.println(ret); // [a, b, e]
final var stream = Stream.of('a', 'b', 'C', 'D', 'e');

final var ret = stream.filter(v -> Character.isUpperCase(v)).toList();
System.out.println(ret); // [C, D]

Optional<T> findAny ()

Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty.

int aaa = 0;
int bbb = 0;
int ccc = 0;

for (int i = 0; i < 1000; i++) {

    final var stream = Stream.of("aaa", "bbb", "ccc").parallel();
    System.out.println(stream.isParallel()); // true

    // "aaa" or "bbb" or "ccc"
    final var opt = stream.findAny();
    if (opt.isEmpty()) {
        throw new IllegalStateException();
    }

    switch (opt.orElseThrow()) {
        case "aaa" -> aaa++;
        case "bbb" -> bbb++;
        case "ccc" -> ccc++;
    }
}

System.out.println("aaa count : " + aaa);
System.out.println("bbb count : " + bbb);
System.out.println("ccc count : " + ccc);

// Result
// ↓
//aaa count : 131
//bbb count : 866
//ccc count : 3
final var stream = Stream.empty();

final var opt = stream.findAny();
System.out.println(opt.isEmpty()); // true

Optional<T> findFirst ()

Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty.

final var stream = Stream.of("aaa", "bbb", "ccc");

final var opt = stream.findFirst();
opt.ifPresent(value -> {
    System.out.println(value); // aaa
});
// parallel
final var stream = Stream.of("aaa", "bbb", "ccc").parallel();
System.out.println(stream.isParallel()); // true

final var opt = stream.findFirst();
opt.ifPresent(value -> {
    System.out.println(value); // aaa
});
int aaa = 0;
int bbb = 0;
int ccc = 0;

for (int i = 0; i < 1000; i++) {

    // unordered and parallel
    final var stream = Stream.of("aaa", "bbb", "ccc").unordered().parallel();

    // "aaa" or "bbb" or "ccc"
    final var opt = stream.findFirst();
    if (opt.isEmpty()) {
        throw new IllegalStateException();
    }

    switch (opt.orElseThrow()) {
        case "aaa" -> aaa++;
        case "bbb" -> bbb++;
        case "ccc" -> ccc++;
    }
}

System.out.println("aaa count : " + aaa);
System.out.println("bbb count : " + bbb);
System.out.println("ccc count : " + ccc);

// Result
// ↓
//aaa count : 209
//bbb count : 788
//ccc count : 3
final var stream = Stream.empty();

final var opt = stream.findFirst();
System.out.println(opt.isEmpty()); // true

<R> Stream<R> flatMap (Function<? super T,? extends Stream<? extends R>> mapper)

Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

final var stream = Stream.of("aaa", "bbb", "ccc");

final var mapper = new Function<String, Stream<String>>() {
    @Override
    public Stream<String> apply(String s) {
        return Stream.of("--", s.toUpperCase(), "++");
    }
};

final var ret = stream.flatMap(mapper).toList();

// [--, AAA, ++, --, BBB, ++, --, CCC, ++]
System.out.println(ret);

DoubleStream flatMapToDouble (Function<? super T,? extends DoubleStream> mapper)

Returns an DoubleStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

final var stream = Stream.of("0x01", "0x02", "0xff");

final var mapper = new Function<String, DoubleStream>() {
    @Override
    public DoubleStream apply(String s) {
        final int num = Integer.decode(s);
        return DoubleStream.of(num, num + 0.1, num + 0.2);
    }
};

final var ret = stream.flatMapToDouble(mapper).toArray();

// [1.0, 1.1, 1.2, 2.0, 2.1, 2.2, 255.0, 255.1, 255.2]
System.out.println(Arrays.toString(ret));

IntStream flatMapToInt (Function<? super T,? extends IntStream> mapper)

Returns an IntStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

final var stream = Stream.of("0x01", "0x02", "0xff");

final var mapper = new Function<String, IntStream>() {
    @Override
    public IntStream apply(String s) {
        final int num = Integer.decode(s);
        return IntStream.of(num, num * 10, num * 100);
    }
};

final var ret = stream.flatMapToInt(mapper).toArray();

// [1, 10, 100, 2, 20, 200, 255, 2550, 25500]
System.out.println(Arrays.toString(ret));

LongStream flatMapToLong (Function<? super T,? extends LongStream> mapper)

Returns an LongStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

final var stream = Stream.of("0x01", "0x02", "0xff");

final var mapper = new Function<String, LongStream>() {
    @Override
    public LongStream apply(String s) {
        final long num = Long.decode(s);
        return LongStream.of(num, num * 10000000000L);
    }
};

final var ret = stream.flatMapToLong(mapper).toArray();

// [1, 10000000000, 2, 20000000000, 255, 2550000000000]
System.out.println(Arrays.toString(ret));

void forEach (Consumer<? super T> action)

Performs an action for each element of this stream.

Please see also : forEachOrdered(Consumer<? super T> action)

final var stream = Stream.of("aaa", "bbb", "ccc");

final var action = new Consumer<String>() {
    @Override
    public void accept(String s) {
        System.out.println(s);
    }
};

System.out.println("-- forEach --");
stream.forEach(action);

// Result
// ↓
//-- forEach --
//aaa
//bbb
//ccc
// An example with a lambda expression.
final var stream = Stream.of("ZZZ", "YYY", "XXX");

System.out.println("-- forEach --");
stream.forEach(v -> {
    System.out.println(v);
});

// Result
// ↓
//ZZZ
//YYY
//XXX
final var stream = Stream.of(10, 20, 30, 40, 50).parallel();
System.out.println(stream.isParallel()); // true

System.out.println("-- forEach --");
stream.forEach(v -> {
    System.out.println(v);
});

// Result
// ↓
//-- forEach --
//30
//50
//40
//10
//20

void forEachOrdered (Consumer<? super T> action)

Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order.

final var stream = Stream.of("aaa", "bbb", "ccc");

final var action = new Consumer<String>() {
    @Override
    public void accept(String s) {
        System.out.println(s);
    }
};

System.out.println("-- forEach --");
stream.forEachOrdered(action);

// Result
// ↓
//-- forEach --
//aaa
//bbb
//ccc
final var stream = Stream.of(10, 20, 30, 40, 50).parallel();
System.out.println(stream.isParallel()); // true

System.out.println("-- forEach --");
stream.forEachOrdered(v -> {
    System.out.println(v);
});

// Result
// ↓
//-- forEach --
//10
//20
//30
//40
//50

static <T> Stream<T> generate (Supplier<? extends T> s)

Returns an infinite sequential unordered stream where each element is generated by the provided Supplier.

final var supplier = new Supplier<Integer>() {
    int count = 0;

    @Override
    public Integer get() {
        count += 10;
        return count;
    }
};

final var stream = Stream.generate(supplier);

final var ret = stream.limit(5).toList();
System.out.println(ret); // [10, 20, 30, 40, 50]

static <T> Stream<T> iterate (T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)

Returns a sequential ordered Stream produced by iterative application of the given next function to an initial element, conditioned on satisfying the given hasNext predicate.

final var hasNext = new Predicate<Integer>() {
    @Override
    public boolean test(Integer i) {
        return i <= 100;
    }
};

final var next = new UnaryOperator<Integer>() {
    @Override
    public Integer apply(Integer i) {
        return i * 2;
    }
};

final var stream = Stream.iterate(1, hasNext, next);

final var ret = stream.toList();
System.out.println(ret); // [1, 2, 4, 8, 16, 32, 64]

static <T> Stream<T> iterate (T seed, UnaryOperator<T> f)

Returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc.

final var next = new UnaryOperator<Integer>() {
    @Override
    public Integer apply(Integer i) {
        return i * 2;
    }
};

final var stream = Stream.iterate(1, next);
final var ret = stream.limit(10).toList();

// [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
System.out.println(ret);

Stream<T> limit (long maxSize)

Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.

final var stream = Stream.of("a", "b", "c", "d", "e", "f", "g");

final var ret = stream.limit(3).toList();
System.out.println(ret); // [a, b, c]

<R> Stream<R> map (Function<? super T,? extends R> mapper)

Returns a stream consisting of the results of applying the given function to the elements of this stream.

final var stream = Stream.of("aaa", "bbb", "ccc");

final var mapper = new Function<String, String>() {
    @Override
    public String apply(String s) {
        return s.toUpperCase();
    }
};

final var ret = stream.map(mapper).toList();
System.out.println(ret); // [AAA, BBB, CCC]
final var stream = Stream.of("AAA", "BBB", "CCC");

final var ret = stream.map(String::toLowerCase).toList();
System.out.println(ret); // [aaa, bbb, ccc]
final var stream = Stream.of("0x01", "0x0a", "0xff");

final var ret = stream.map(s -> Integer.decode(s) * 10).toList();
System.out.println(ret); // [10, 100, 2550]

default <R> Stream<R> mapMulti (BiConsumer<? super T,? super Consumer<R>> mapper)

Returns a stream consisting of the results of replacing each element of this stream with multiple elements, specifically zero or more elements.

final var stream = Stream.<Number>of(
        100, 200, // Integer
        3.0, 4.0, // Double
        5000000000L, 6000000000L // Long
);

final var mapper = new BiConsumer<Number, Consumer<String>>() {
    @Override
    public void accept(Number number, Consumer<String> consumer) {
        if (number instanceof Integer i) {
            consumer.accept("num=" + i);
            consumer.accept("num=" + (i + 1));
            consumer.accept("num=" + (i + 2));
        }
    }
};

final var ret = stream.mapMulti(mapper).toList();

// [num=100, num=101, num=102, num=200, num=201, num=202]
System.out.println(ret);

default DoubleStream mapMultiToDouble (BiConsumer<? super T,? super DoubleConsumer> mapper)

Returns a DoubleStream consisting of the results of replacing each element of this stream with multiple elements, specifically zero or more elements.

final var stream = Stream.<Number>of(
        100, 200, // Integer
        3.0, 4.0, // Double
        5000000000L, 6000000000L // Long
);

final var ret = stream.mapMultiToDouble((number, consumer) -> {
    if (number instanceof Double d) {
        consumer.accept(d);
        consumer.accept(d + 0.1);
        consumer.accept(d + 0.2);

    }
}).toArray();

// [3.0, 3.1, 3.2, 4.0, 4.1, 4.2]
System.out.println(Arrays.toString(ret));

default IntStream mapMultiToInt (BiConsumer<? super T,? super IntConsumer> mapper)

Returns an IntStream consisting of the results of replacing each element of this stream with multiple elements, specifically zero or more elements.

final var stream = Stream.<Number>of(
        100, 200, // Integer
        3.0, 4.0, // Double
        5000000000L, 6000000000L // Long
);

final var ret = stream.mapMultiToInt((number, consumer) -> {
    if (number instanceof Integer i) {
        consumer.accept(i);
        consumer.accept(i + 1);
        consumer.accept(i + 2);
    }
}).toArray();

// [100, 101, 102, 200, 201, 202]
System.out.println(Arrays.toString(ret));

default LongStream mapMultiToLong (BiConsumer<? super T,? super LongConsumer> mapper)

Returns a LongStream consisting of the results of replacing each element of this stream with multiple elements, specifically zero or more elements.

final var stream = Stream.<Number>of(
        100, 200, // Integer
        3.0, 4.0, // Double
        5000000000L, 6000000000L // Long
);

final var ret = stream.mapMultiToLong((number, consumer) -> {
    if (number instanceof Long l) {
        consumer.accept(l);
        consumer.accept(l + 1);
    }
}).toArray();

// [5000000000, 5000000001, 6000000000, 6000000001]
System.out.println(Arrays.toString(ret));

DoubleStream mapToDouble (ToDoubleFunction<? super T> mapper)

Returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.

final var stream = Stream.of(100, 125, 200);

final var mapper = new ToDoubleFunction<Integer>() {
    @Override
    public double applyAsDouble(Integer value) {
        return value / 2.0;
    }
};

final var ret = stream.mapToDouble(mapper).toArray();
System.out.println(Arrays.toString(ret)); // [50.0, 62.5, 100.0]

IntStream mapToInt (ToIntFunction<? super T> mapper)

Returns an IntStream consisting of the results of applying the given function to the elements of this stream.

final var stream = Stream.of("0x01", "0x0a", "0xff");

final var mapper = new ToIntFunction<String>() {
    @Override
    public int applyAsInt(String value) {
        return Integer.decode(value);
    }
};

final var ret = stream.mapToInt(mapper).toArray();
System.out.println(Arrays.toString(ret)); // [1, 10, 255]

LongStream mapToLong (ToLongFunction<? super T> mapper)

Returns a LongStream consisting of the results of applying the given function to the elements of this stream.

final var stream = Stream.of("0x01", "0x0a", "0xffffffffffffff");

final var mapper = new ToLongFunction<String>() {
    @Override
    public long applyAsLong(String value) {
        return Long.decode(value);
    }
};

final var ret = stream.mapToLong(mapper).toArray();
System.out.println(Arrays.toString(ret)); // [1, 10, 72057594037927935]

Optional<T> max (Comparator<? super T> comparator)

Returns the maximum element of this stream according to the provided Comparator.

final var stream = Stream.of(10, 5, 100, 30);

final var comparator = new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        return Integer.compare(o1, o2);
    }
};

final var opt = stream.max(comparator);
opt.ifPresent(value -> {
    System.out.println(value); // 100
});
final var stream = Stream.of("aaa", "ddd", "ccc", "bbb");

final var opt = stream.max(Comparator.naturalOrder());
opt.ifPresent(value -> {
    System.out.println(value); // ddd
});
final var stream = Stream.<String>empty();

final var opt = stream.max(String.CASE_INSENSITIVE_ORDER);
System.out.println(opt.isEmpty()); // true

Optional<T> min (Comparator<? super T> comparator)

Returns the minimum element of this stream according to the provided Comparator.

final var stream = Stream.of(10, 5, 100, 30);

final var comparator = new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        return Integer.compare(o1, o2);
    }
};

final var opt = stream.min(comparator);
opt.ifPresent(value -> {
    System.out.println(value); // 5
});
final var stream = Stream.of("ccc", "ddd", "aaa", "bbb");

final var opt = stream.min(Comparator.naturalOrder());
opt.ifPresent(value -> {
    System.out.println(value); // aaa
});
final var stream = Stream.<String>empty();

final var opt = stream.min(String.CASE_INSENSITIVE_ORDER);
System.out.println(opt.isEmpty()); // true

boolean noneMatch (Predicate<? super T> predicate)

Returns whether no elements of this stream match the provided predicate.

final var predicate = new Predicate<Character>() {
    @Override
    public boolean test(Character c) {
        // Checks if the character is lowercase.
        return Character.isLowerCase(c);
    }
};

{
    final var stream = Stream.of('a', 'b', 'c');

    final var ret = stream.noneMatch(predicate);
    System.out.println(ret); // false
}
{
    final var stream = Stream.of('A', 'b', 'c');

    final var ret = stream.noneMatch(predicate);
    System.out.println(ret); // false
}
{
    final var stream = Stream.of('A', 'B', 'C');

    final var ret = stream.noneMatch(predicate);
    System.out.println(ret); // true
}

static <T> Stream<T> of (T t)

Returns a sequential Stream containing a single element.

final var stream = Stream.of("aaa");

final var ret = stream.toList();
System.out.println(ret); // [aaa]
final var stream = Stream.of(123);

final var ret = stream.toList();
System.out.println(ret); // [123]

static <T> Stream<T> of (T... values)

Returns a sequential ordered stream whose elements are the specified values.

final var stream = Stream.of("aaa", "bbb");

final var ret = stream.toList();
System.out.println(ret); // [aaa, bbb]
final var stream = Stream.of("aaa", "bbb", "ccc");

final var ret = stream.toList();
System.out.println(ret); // [aaa, bbb, ccc]
final var stream = Stream.of(1, 3, 5, 7, 9);

final var ret = stream.toList();
System.out.println(ret); // [1, 3, 5, 7, 9]

static <T> Stream<T> ofNullable (T t)

Returns a sequential Stream containing a single element, if non-null, otherwise returns an empty Stream.

final var stream = Stream.ofNullable("aaa");

final var ret = stream.toList();
System.out.println(ret); // [aaa]
final var stream = Stream.ofNullable(123);

final var ret = stream.toList();
System.out.println(ret); // [123]
final var stream = Stream.ofNullable(null);

final var ret = stream.count();
System.out.println(ret); // 0

Stream<T> peek (Consumer<? super T> action)

Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.

final var stream = Stream.of("aaa", "bbb", "ccc");

final var action = new Consumer<String>() {
    @Override
    public void accept(String value) {
        System.out.println("peek : value = " + value);
    }
};

final var list = stream.peek(action).toList();
System.out.println("list = " + list);

// Result
// ↓
//peek : value = aaa
//peek : value = bbb
//peek : value = ccc
//list = [aaa, bbb, ccc]

Optional<T> reduce (BinaryOperator<T> accumulator)

Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.

final var stream = Stream.of("a", "b", "c");

final var accumulator = new BinaryOperator<String>() {
    @Override
    public String apply(String s1, String s2) {
        return s1 + "-" + s2;
    }
};

final var opt = stream.reduce(accumulator);
opt.ifPresent(value -> {
    System.out.println(value); // a-b-c
});
final var stream = Stream.<String>empty();

final var ret = stream.reduce((s1, s2) -> s1 + "-" + s2);
System.out.println(ret.isEmpty()); // true

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

Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value.

final var stream = Stream.of("a", "b", "c");
final var identity = "";

final var accumulator = new BinaryOperator<String>() {
    @Override
    public String apply(String s1, String s2) {
        if (s1.isEmpty()) {
            return s2;
        }

        return s1 + "-" + s2;
    }
};

final var ret = stream.reduce(identity, accumulator);
System.out.println(ret); // a-b-c
final var stream = Stream.<String>empty();
final var identity = "";

final var ret = stream.reduce(identity, (s1, s2) -> {
    if (s1.isEmpty()) {
        return s2;
    }
    return s1 + "-" + s2;
});

System.out.println(ret.isEmpty()); // true

<U> U reduce (U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner)

Performs a reduction on the elements of this stream, using the provided identity, accumulation and combining functions.

final var stream = Stream.of(1, 10, 255).parallel();
System.out.println(stream.isParallel()); // true

final var identity = "";

final var accumulator = new BiFunction<String, Integer, String>() {
    @Override
    public String apply(String s, Integer i) {
        final var hex = "0x" + Integer.toHexString(i);

        if (s.isEmpty()) {
            return hex;
        }

        return s + "-" + hex;
    }
};

final var combiner = new BinaryOperator<String>() {
    @Override
    public String apply(String s1, String s2) {
        if (s1.isEmpty()) {
            return s2;
        }

        return s1 + "-" + s2;
    }
};

final var ret = stream.reduce(identity, accumulator, combiner);
System.out.println(ret); // 0x1-0xa-0xff

Stream<T> skip (long n)

Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream.

final var stream = Stream.of("a", "b", "c", "d", "e", "f", "g");

final var ret = stream.skip(4).toList();
System.out.println(ret); // [e, f, g]

Stream<T> sorted ()

Returns a stream consisting of the elements of this stream, sorted according to natural order.

final var stream = Stream.of("aaa", "ddd", "ccc", "bbb");

final var ret = stream.sorted().toList();
System.out.println(ret); // [aaa, bbb, ccc, ddd]
final var stream = Stream.of(5, 3, 2, 4, 1).parallel();
System.out.println(stream.isParallel()); // true

final var ret = stream.sorted().toList();
System.out.println(ret); // [1, 2, 3, 4, 5]

Stream<T> sorted (Comparator<? super T> comparator)

Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.

final var stream = Stream.of("aaa", "ddd", "ccc", "bbb");

final var ret = stream.sorted(Comparator.reverseOrder()).toList();
System.out.println(ret); // [ddd, ccc, bbb, aaa]
final var stream = Stream.of(1, 3, 2, 5, 4).parallel();
System.out.println(stream.isParallel()); // true

final var ret = stream.sorted(Comparator.reverseOrder()).toList();
System.out.println(ret); // [5, 4, 3, 2, 1]

default Stream<T> takeWhile (Predicate<? super T> predicate)

Returns, if this stream is ordered, a stream consisting of the longest prefix of elements taken from this stream that match the given predicate.

final var stream = Stream.of("aa", "bb", "cc", "dd", "ee", "ff");

final var predicate = new Predicate<String>() {
    @Override
    public boolean test(String s) {
        return !s.equals("dd");
    }
};

final var ret = stream.takeWhile(predicate).toList();
System.out.println(ret); // [aa, bb, cc]
final var stream = Stream.of(1, 2, 3, 4, 5);

final var ret = stream.takeWhile(v -> v != 4).toList();
System.out.println(ret); // [1, 2, 3]

Object[] toArray ()

Returns an array containing the elements of this stream.

final var stream = Stream.of("aaa", "bbb", "ccc");

final var ret = stream.toArray();
System.out.println(Arrays.toString(ret)); // [aaa, bbb, ccc]
final var stream = Stream.of(1, 3, 100);

final var ret = stream.toArray();
System.out.println(Arrays.toString(ret)); // [1, 3, 100]

<A> A[] toArray (IntFunction<A[]> generator)

Returns an array containing the elements of this stream, using the provided generator function to allocate the returned array, as well as any additional arrays that might be required for a partitioned execution or for resizing.

final var stream = Stream.of("aaa", "bbb", "ccc");

final var generator = new IntFunction<String[]>() {
    @Override
    public String[] apply(int value) {
        return new String[value];
    }
};

final String[] ret = stream.toArray(generator);
System.out.println(Arrays.toString(ret)); // [aaa, bbb, ccc]
final var stream = Stream.of("aaa", "bbb", "ccc");

// An example with a method reference expression.
final String[] ret = stream.toArray(String[]::new);
System.out.println(Arrays.toString(ret)); // [aaa, bbb, ccc]

default List<T> toList ()

Accumulates the elements of this stream into a List.

final var stream = Stream.of("aaa", "bbb", "ccc");

final var list = stream.toList();
System.out.println(list); // [aaa, bbb, ccc]

try {
    list.add("ddd");
} catch (UnsupportedOperationException e) {
    System.out.println("UnsupportedOperationException!");
}

// Result
// ↓
//UnsupportedOperationException!
final var stream = Stream.of(1, 3, 100);

final var list = stream.toList();
System.out.println(list); // [1, 3, 100]

Methods declared in BaseStream

close, isParallel, iterator, onClose, parallel, sequential, spliterator, unordered

Please see the link below.


Related posts

To top of page