Stream forEach(Consumer action) example

Description

Stream forEach(Consumer<? super T> action) performs an action for each element of this stream.

Syntax

forEach has the following syntax.


void forEach(Consumer<? super T> action)

Example

The following example shows how to use forEach.


import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
//from  w  ww  .  j  a v  a  2s  . c  om
public class Main {
  public static void main(String[] args) {
    List<String> stringList = Arrays.asList("1","1","2","3","4");

    stringList.stream()      
              .sorted(Comparator.reverseOrder())
              .forEach(System.out::println);
  }
}

The code above generates the following result.





















Home »
  Java Streams »
    Reference »




Collectors
DoubleStream
DoubleStream.Builder
IntStream
IntStream.Builder
LongStream
LongStream.Builder
Stream
Stream.Builder