limit() example
Example:
import java.util.Arrays;
import java.util.List;
public class LimitFlight {
public static void main(String[] args) {
System.out.println("main() [Start]");
List<Integer> numbers = Arrays.asList(6,10, 20, 10, 3, 3, 2,
4,6,9,8,9,8,9);
numbers
.stream()
.filter(num->num%2==0)
.distinct()
.limit(4)
.forEach(System.out::println);
System.out.println("main() [End]");
}
}
Ouput:
main() [Start]
6
10
20
2
main() [End]
Explanation:
.filter(num->num%2==0) :
- filter takes the lamda expression as an argument.
- It takes a lamda expression having functional interface having abstract method which take one argument and return boolean result.
- It returns the Stream of given type parameter.
- this method works on the stream returned from the filter method
- It returns the Stream with unique element.
- this method works on the stream returned from the filter method
- It returns the Stream with 4 elements only.
- As its name, it curb the Stream to 4 elements only.
- This method works on the stream returned from the limit method
- This is a terminal operation method because it doesnt return the stream.
- All the previous streams maintained as pipeline and processed when this method get called
- This method takes a consumer functional interface lamda expression or method reference as argument and it consumes the data of previous streams. Here it consumes and display each element.