How to use flatMap in IntStream?

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

Syntax:

Modifier and Type                Method
IntStream 	                     flatMap(IntFunction<? extends IntStream> mapper)
package com.nourit.java8.Streams.IntStream;

import java.util.stream.IntStream;

public class IntStreamFlatMap {

  public static void main(String[] args) {
    System.out.println("---------- FlatMap Example 1 -----------------");
    // The process of mapping each element of this stream with the contents
    // of a mapped stream produced by applying the provided mapping function
    // to each element.
    IntStream intStream = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8).flatMap(n -> IntStream.of(n*n));
    intStream.forEach(System.out::println);
    System.out.println("---------- FlatMap Example 2 -----------------");
    // The process of mapping each element of this stream with the contents
    // of a mapped stream produced by applying the provided mapping function
    // to each element.
    IntStream intStream1 = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8).flatMap(n -> IntStream.of(n+n));
    intStream1.forEach(System.out::println);
    System.out.println("---------- FlatMap Example 3 -----------------");
    // The process of mapping each element of this stream with the contents
    // of a mapped stream produced by applying the provided mapping function
    // to each element.
    IntStream emptyStream = IntStream.empty().flatMap(n -> IntStream.of(n+n));
    if (emptyStream.count() == 0) {
      System.out.println("Is Empty");
    } else {
      emptyStream.forEach(System.out::println);
    }
    System.out.println("---------------------------------------");
  }
}

Output:

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

 

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.

*