Java Streams - Stream forEach(Consumer action) example








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;
/*ww w.ja  v  a  2s  .c o  m*/
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.