How to use forEachOrdered in IntStream?

Here is an example to explain how to use forEachOrdered in IntStream.

Syntax:

Modifier and Type               Method
void                            forEachOrdered(IntConsumer action)
package com.nourit.java8.Streams.IntStream;

import java.util.stream.IntStream;

public class IntStreamforEachOrdered {

  public static void main(String[] args) {
    System.out.println("---------- ForEachOrdered Example 1 -----------------");
    // Performs an action for each element of this stream, guaranteeing that each element is processed in encounter order for streams that have a defined encounter order.
    IntStream intStream1 = IntStream.of(8, 7, 6, 5, 4, 3, 2, 1);
    intStream1.forEachOrdered(System.out::println);
    System.out.println("---------- ForEachOrdered Example 2 -----------------");
    // Performs an action for each element of this stream, guaranteeing that each element is processed in encounter order for streams that have a defined encounter order.
    IntStream intStream2 = IntStream.of(8, 7, 6, 5, 4, 3, 2, 1).flatMap(n -> IntStream.of(n*n));
    intStream2.forEachOrdered(System.out::println);
    System.out.println("---------- ForEachOrdered Example 3 -----------------");
    // Performs an action for each element of this stream, guaranteeing that each element is processed in encounter order for streams that have a defined encounter order.
    IntStream intStream3 = IntStream.of(8, 7, 6, 5, 4, 3, 2, 1).flatMap(n -> IntStream.of(n+n));
    intStream3.forEachOrdered(System.out::println);
    System.out.println("---------------------------------------");
  }
}

Output:

---------- ForEachOrdered Example 1 -----------------
8
7
6
4
5
3
2
1
---------- ForEachOrdered Example 2 -----------------
64
49
36
25
16
9
4
1
---------- ForEachOrdered Example 3 -----------------
16
14
12
10
8
6
4
2
---------------------------------------

 

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*