Java Stream forEach operation

Introduction

The forEach() method has this general form:

void forEach(Consumer<? super T>  action) 

import java.util.ArrayList;
import java.util.stream.Stream;

public class Main {

  public static void main(String[] args) {

    // Create a list of Integer values.
    ArrayList<Integer> myList = new ArrayList<>();
    myList.add(7);//w w w  .  java 2s  .c om
    myList.add(8);
    myList.add(1);
    myList.add(2);
    myList.add(7);
    myList.add(5);

    System.out.println("Original list: " + myList);

    Stream<Integer> myStream = myList.stream();

    // Sort the stream by use of sorted().
    Stream<Integer> sortedStream = myStream.sorted();

    // Display the sorted stream by use of forEach().
    System.out.print("Sorted stream: ");
    sortedStream.forEach((n) -> System.out.print(n + " "));
    System.out.println(); 
  }
}



PreviousNext

Related