Close

Java 8 Streams - Stream.forEach Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.Stream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.StreamStreamLogicBig

Method:

void forEach(Consumer<? super T> action)

This terminal operation performs an action for each element of this stream.


Examples


package com.logicbig.example.stream;

import java.util.stream.Stream;

public class ForEachExample {

public static void main(String... args) {
Stream<String> s = Stream.of("one", "two", "three", "four");
s.forEach(System.out::println);
}
}

Output

one
two
three
four




         Arrays.stream(Thread.currentThread()
.getStackTrace())
.forEach(System.out::println);
System.out.println(method);
Original Post




Stream.forEach(Consumer), IntStream.forEach(Consumer), LongStream.forEach(LongConsumer), DoubleStream.forEach(DoubleConsumer), all these terminal operations allow client code to take consumer actions on each element of this stream. These methods do not respect the encounter order, whereas, Stream .forEachOrdered(Consumer), LongStream.forEachOrdered(LongConsumer), DoubleStream .forEachOrdered(DoubleConsumer) methods preserve encounter order but are not good in performance for parallel computations.

package com.logicbig.example;

import java.util.Arrays;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;

public class ForEachExample {

public static void main (String[] args) {
final int[] ints = IntStream.range(0, 5).toArray();
PerformanceTestUtil.runTest("forEach() method", () -> {
Arrays.stream(ints).parallel().forEach(i -> doSomething(i));
});

PerformanceTestUtil.runTest("forEachOrdered() method", () -> {
Arrays.stream(ints).parallel().forEachOrdered(i -> doSomething(i));
});
}

private static void doSomething (int i) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s, ", i);
}
}

Output

3, 2, 0, 4, 1, forEach() method time taken: 15.41 milliseconds
0, 1, 2, 3, 4, forEachOrdered() method time taken: 77.55 milliseconds
Original Post




A wrong way to use side effect via forEach, use terminal operation Stream.collect instead.

package com.logicbig.example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

public class SideEffectWrongUse {

public static void main (String[] args) {
List<Integer> results = new ArrayList<>();
IntStream.range(0, 150)
.parallel()
.filter(s -> s % 2 == 0)
.forEach(s -> results.add(s));//stateful side effect
//not thread safe
System.out.println(results);
}
}

Output

[98, 100, 94, 96, 108, 110, 102, 104, 106, 84, 86, 88, 90, 92, 80, 82, 76, 78, 22, 24, 26, 46, 48, 50, 18, 20, 52, 54, 32, 42, 34, 44, 36, 38, 28, 40, 30, 66, 68, 10, 12, 70, 72, 14, 74, 16, 60, 4, 62, 6, 64, 8, 56, 0, 58, 2, 126, 116, 118, 128, 120, 130, 136, 138, 112, 122, 146, 114, 124, 148, 132, 134, 140, 142, 144]
Original Post
    private static void printMap (Map<?, ?> map) {
map.entrySet()
.stream().limit(15)
.forEach(e -> System.out.println(e.getKey() + " = " + e.getValue()));
System.out.println("-------------");

}
Original Post




See Also