Skip to content

Commit e8daf43

Browse files
committed
added skip() and limit() Stream Operation
1 parent b4bb8c2 commit e8daf43

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.learn.streams;
2+
3+
import java.util.List;
4+
import java.util.Optional;
5+
6+
public class StreamsLimitSkipExample {
7+
8+
public static void main(String[] args) {
9+
10+
List<Integer> integerList = List.of(10, 20, 30, 40, 50);
11+
12+
Optional<Integer> sum = sumWithLimit(integerList);
13+
if (sum.isPresent()) {
14+
System.out.println("Limit Sum : " + sum.get());
15+
}
16+
17+
Optional<Integer> sumWithSkip = sumWithSkip(integerList);
18+
if (sumWithSkip.isPresent()) {
19+
System.out.println("Skip Sum : " + sumWithSkip.get());
20+
}
21+
}
22+
23+
public static Optional<Integer> sumWithLimit(List<Integer> integerList) {
24+
return integerList.stream()
25+
.limit(2)
26+
// only 10 and 20 will be passed to reduce function
27+
.reduce(Integer::sum);
28+
}
29+
30+
public static Optional<Integer> sumWithSkip(List<Integer> integerList) {
31+
return integerList.stream()
32+
// first 3 numbers are skipped
33+
.skip(3)
34+
//it passes only 40 and 50.
35+
.reduce(Integer::sum);
36+
}
37+
38+
39+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ This repository contains the basic &amp; advance level examples related to Java
3333
* [reduce()](Modern-Java-Examples/src/com/learn/streams/StreamsReduceExample.java)
3434
* [map() + filter() + reduce()](Modern-Java-Examples/src/com/learn/streams/StreamMapReduceExample.java)
3535
* [max and min using reduce()](Modern-Java-Examples/src/com/learn/streams/StreamsMinMaxExample.java)
36+
* [skip() and limit()](Modern-Java-Examples/src/com/learn/streams/StreamsLimitSkipExample.java)
3637

3738

3839

0 commit comments

Comments
 (0)