range() rangeClosed() 차이

# range() rangeClosed()

자바8에 추가된 API로 원시 데이터 형 int와 long를 스트림으로 다룰 수 있도록 해준다.

public static IntStream range(int startInclusive, int endExclusive) {
    ...
}

public static IntStream rangeClosed(int startInclusive, int endInclusive) {
    ...
}
1
2
3
4
5
6
7

# range() rangeClosed() 차이

두번째 파리미터를 범위에 포함하느냐 안하느냐 차이. 개인적으로 rangeClosed가 가독성이 좋아서 선호한다.

IntStream.range(1,5) generates a stream of ‘1,2,3,4’

LongStream.rangeClosed(1,5) generates a stream of ‘1,2,3,4,5'

# Example

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

        System.out.println("range()");
        IntStream.range(0, 5)
                .forEach(System.out::println);

        System.out.println("------------------");

        System.out.println("rangeClosed()");
        IntStream.rangeClosed(0, 5)
                .forEach(System.out::println);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

result

range()
0
1
2
3
4
------------------
rangeClosed()
0
1
2
3
4
5
1
2
3
4
5
6
7
8
9
10
11
12
13
14