Get rid of boring for loop and try using "range" and "rangeClosed"

Most of the Java developer already started using Java 15 but here is the feature in java 8  which  i want  to introduce to the people who doesn't  know about it or may be not using it. Lets see about two static methods 

"range()" and "rangeClosed()".

Usage 

These two methods are available in IntStream and LongStream.


IntStream - IntStream class is an specialization of Stream interface for int primitive. It represents an stream of primitive int-valued elements supporting sequential and parallel aggregate operations. 

IntStream is part of the java. util. stream package and implements AutoCloseable and BaseStream interfaces.

Syntax

range

It returns the sequential ordered IntStream .It includes only the startInclusive value .

static IntStream range(int startInclusiveint endInclusive)

rangeClosed

It returns the sequential ordered IntStream .It includes startInclusive and endInclusive values .

static IntStream rangeClosed(int startInclusive, int endInclusive)

LongStream - LongStream class is an specialization of Stream interface for Long primitive A sequence of primitive long-valued elements supporting sequential and parallel aggregate operations. 


Syntax

range

It returns the sequential ordered LongStream .It includes only the startInclusive value .

static LongStream range(long startInclusivelong endInclusive)

rangeClosed

It returns the sequential ordered LongStream .It includes startInclusive and endInclusive values .

static LongStream rangeClosed(long startInclusivelong endInclusive)


Example

public class RangeAndRangeClosed {

    public static void main(String args[]){
IntStream.range(1,10).forEach(System.out::println);
System.out.println();

IntStream.rangeClosed(1,10).forEach(System.out::println);
System.out.println();

LongStream.range(1000000L, 1000005L).forEach(System.out::println);
}
}
Output 
1
2
3
4
5
6
7
8
9

1
2
3
4
5
6
7
8
9
10

1000000
1000001
1000002
1000003
1000004

Comments

Post a Comment

Popular posts from this blog

Custom Exception Handling For Spring Boot Rest Controller

HOW TO USE NOTE PAD AS YOUR PERSONAL DAIRY!!!!!