본문 바로가기
개발&프로그래밍

[JAVA] Java8 Stream Skip()과 limit()

by 재아군 2022. 3. 14.

 

Java Stream API의 Skip()과 limit()에 대해서 유사한점과 차이점을 알아봅니다.

 

 

 

skip(n) 

Stream의 처음 n개의 요소를 버리는 작업입니다. 

 

skip(long n)
Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream.

 

스트림의 첫 번째 요소를 버린 후 이 스트림의 나머지 요소로 구성된 스트림을 반환합니다  이 스트림에 요소보다 적은 수 n의 요소가 포함되어 있으면 빈 스트림이 반환됩니다. 이것은 상태 저장 중간 작업(stateful intermediate operation) 입니다.

 

 

Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    .filter(i -> i % 2 == 0)
    .skip(2)
    .forEach(i -> System.out.print(i + " ")); //output: 6 8 10

Stream의 짝수 번호를 필터링한후, 처음 2개를 버리고 그 다음 forEach문에서 결과를 출력합니다.

 

 


 

 

limit(n)

이 스트림의 요소로 구성된 스트림 maxSize을 길이보다 길지 않게 잘린 스트림을 반환합니다.
이것은 단락 상태 저장 중간 작업(short-circuiting stateful intermediate operation) 입니다.

 

limit(long maxSize)

Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.

 

Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    .filter(i -> i % 2 == 0)
    .limit(2)
    .forEach(i -> System.out.print(i + " ")); //output: 2 4

 

전체 스트림을 소비하는 skip()과 달리 limit()는 최대 항목 수에 도달하는 즉시 더 이상 element를 소비하지 않고 결과 스트림을 반환합니다.

 

댓글