How to use forEach in IntStream?

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

Syntax:

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

import java.util.stream.IntStream;

public class IntStreamForEach {

	public static void main(String[] args) {
		System.out.println("---------- ForEach Example 1 -----------------");
		// Performs an action for each element of this stream.
		IntStream intStream1 = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8);
		intStream1.forEach(System.out::println);
		System.out.println("---------- ForEach Example 2 -----------------");
		// Performs an action for each element of this stream.
		IntStream intStream2 = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8).flatMap(n -> IntStream.of(n*n));
		intStream2.forEach(System.out::println);
		System.out.println("---------- ForEach Example 3 -----------------");
		// Performs an action for each element of this stream.
		IntStream intStream3 = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8).flatMap(n -> IntStream.of(n+n));
		intStream3.forEach(System.out::println);
		System.out.println("---------------------------------------");
	}
}

Output:

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

 

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.

*