How to create a IntStream in Java 8?

There are some examples to create an intstream.

  • Firsth example to create an intstream with of (Collection of known values / objects)
package com.nourit.java8.Streams.IntStream;

import java.util.stream.IntStream;

public class CreateIntStreamWithOf {

  public static void main(String[] args) {
    //Collection of known values / objects
    IntStream intStream = IntStream.of(1, 2, 3, 4, 5);
    //Output: 12345 
    intStream.forEach(System.out::print);
  }
}
  • Seconde example to create an intstream with Range(startInclusive, endExclusive)

Creates a list of all numbers from 1 to 4 in java 8

package com.nourit.java8.Streams.IntStream;

import java.util.stream.IntStream;

public class CreateIntStreamWithRange {

  public static void main(String[] args) {
    // 1 <= value < 5
    IntStream intStream = IntStream.range(1, 5);
    // Output: 1234
    intStream.forEach(System.out::print);
  }

}
  • Third example to create an intstream with RangeClosed(startInclusive, endInclusive)

Creates a list of all numbers from 1 to 5 in java 8

package com.nourit.java8.Streams.IntStream;

import java.util.stream.IntStream;

public class CreateIntStreamWithRangeClosed {

  public static void main(String[] args) {
    // 1 <= value <= 5  rangeClosed(startInclusive, endInclusive)
    IntStream intStream = IntStream.rangeClosed(1, 5);
    // Output: 12345
    intStream.forEach(System.out::print);
  }

}
  • Fourth example to create an intstream with iterate

Creates a list of all numbers from 0 to 9 in java 8

package com.nourit.java8.Streams.IntStream;

import java.util.stream.IntStream;

public class CreateIntStreamWithIterate {

  public static void main(String[] args) {
     // Creates a list of all numbers from 0 to 9
    IntStream intStream = IntStream.iterate(0, i -> i + 1)
                .limit(10);
    // Output: 0123456789
    intStream.forEach(System.out::print);
  }
}

 

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.

*