Java 8 – How to convert IntStream to int or int[]

Few Java 8 examples to get a primitive int from an IntStream.

1. IntStream -> int

Java8Example1.java

package com.mkyong;

import java.util.Arrays;
import java.util.OptionalInt;
import java.util.stream.IntStream;

public class Java8Example1 {

    public static void main(String[] args) {

        int[] num = {1, 2, 3, 4, 5};

        //1. int[] -> IntStream
        IntStream stream = Arrays.stream(num);

        // 2. OptionalInt
        OptionalInt first = stream.findFirst();

        // 3. getAsInt()
        int result = first.getAsInt();

        System.out.println(result);                                     // 1

        // one line
        System.out.println(Arrays.stream(num).findFirst().getAsInt());  // 1

    }

}

Output


1
1
Java8Example2.java

package com.mkyong;

import java.util.Arrays;
import java.util.OptionalInt;
import java.util.stream.IntStream;

public class Java8Example2 {

    public static void main(String[] args) {

        int[] num = {1, 2, 3, 4, 5};

        //1. int[] -> IntStream
        IntStream stream = Arrays.stream(num);

        // 2. OptionalInt
        OptionalInt any = stream.filter(x -> x % 2 == 0).findAny();

        // 3. getAsInt()
        int result = any.getAsInt();

        System.out.println(result); // 2 or 4

    }

}

Output


2 or 4

2. IntStream -> int[] or Integer[]

Java8Example3.java

package com.mkyong;

import java.util.Arrays;
import java.util.stream.IntStream;

public class Java8Example3 {

    public static void main(String[] args) {

        int[] num = {1, 2, 3, 4, 5};

        IntStream stream = Arrays.stream(num);

        // IntStream -> int[]
        int[] ints = stream.toArray();

        IntStream stream2 = Arrays.stream(num);

        // IntStream -> Integer[]
        Integer[] integers = stream2.boxed().toArray(Integer[]::new);

    }

}

References

author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar