Skip to content

Commit 17191d0

Browse files
committed
BAEL-2977 - skip vs limit in streams
1 parent 130d087 commit 17191d0

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.baeldung.stream;
2+
3+
import java.util.List;
4+
import java.util.stream.Collectors;
5+
import java.util.stream.Stream;
6+
7+
public class SkipLimitComparison {
8+
9+
public static void main(String[] args) {
10+
skipExample();
11+
limitExample();
12+
limitInfiniteStreamExample();
13+
getEvenNumbers(10, 10).stream()
14+
.forEach(System.out::println);
15+
}
16+
17+
public static void skipExample() {
18+
Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
19+
.filter(i -> i % 2 == 0)
20+
.skip(2)
21+
.forEach(i -> System.out.print(i + " "));
22+
}
23+
24+
public static void limitExample() {
25+
Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
26+
.filter(i -> i % 2 == 0)
27+
.limit(2)
28+
.forEach(i -> System.out.print(i + " "));
29+
}
30+
31+
public static void limitInfiniteStreamExample() {
32+
Stream.iterate(0, i -> i + 1)
33+
.filter(i -> i % 2 == 0)
34+
.limit(10)
35+
.forEach(System.out::println);
36+
}
37+
38+
private static List<Integer> getEvenNumbers(int offset, int limit) {
39+
return Stream.iterate(0, i -> i + 1)
40+
.filter(i -> i % 2 == 0)
41+
.skip(offset)
42+
.limit(limit)
43+
.collect(Collectors.toList());
44+
}
45+
46+
}

0 commit comments

Comments
 (0)