Arrays.stream(long[], int, int) in Java

Arrays.stream(long[], int, int): This method is available in java.util.Arrays class of Java.

Syntax:

LongStream java.util.Arrays.stream(long[] array, int startInclusive, int endExclusive)

This method takes three arguments one of type long array and the rest two are of type int as its parameters. This method returns a sequential LongStream with the specified range of the specified array as its source.

Parameters: Three parameters are required for this method.

array: the array, assumed to be unmodified during use.

startInclusive: the first index to cover, inclusive.

endExclusive: index immediately past the last index to cover.

Returns: a LongStream for the array range.

Throws:

1. ArrayIndexOutOfBoundsException - if startInclusive is negative, endExclusive is less than startInclusive, or endExclusive is greater than the array size.

Approach 1: When no exceptions

Java

import java.util.Arrays;

public class Arraysstreamlongrange {
    public static void main(String[] args) {

        long array[] = { 1, 2, 10, 5, 67, 8, 9, 10 };

        int startInclusive = 1, endExclusive = 4;

        System.out.println(Arrays.stream(array,
startInclusive, endExclusive).count());
    }
}

Output:

3


Approach 2: ArrayIndexOutOfBoundsException 

Java

import java.util.Arrays;

public class Arraysstreamlongrange {
    public static void main(String[] args) {

        long array[] = { 1, 2, 10, 5, 67, 8, 9, 10 };

        int startInclusive = 5, endExclusive = 4;

        System.out.println(Arrays.stream(array,
startInclusive, endExclusive).count());
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: origin(5) > fence(4) at java.base/java.util.Spliterators.checkFromToBounds(Spliterators.java:387) at java.base/java.util.Spliterators.spliterator(Spliterators.java:305) at java.base/java.util.Arrays.spliterator(Arrays.java:5373) at java.base/java.util.Arrays.stream(Arrays.java:5506)


No comments:

Post a Comment