
1. preface
Java 8 Stream API ofskip()
andlimit()
Methods have a similar effect. They are both intermediate methods of clipping flows. Today we will discuss these two methods.
2. skip()
skip(lang n)
It's a pre-skip n
Intermediate flow operations of each element. We wrote a simple method to do thisskip
Operate to print out the remaining elements of the flow.
public static void skip(long n) {
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6);
integerStream.skip(n).forEach(integer -> System.out.println("integer = " + integer));
}
After testing, when n < 0
When it was directly thrown out IllegalArgumentException
abnormal. After all, you have to skip some elements. Just like playing chess, you can't retreat but move forward. when n=0
At that time, he returned it intact. Generally, we will not take the initiative to do this kind of operation and it is meaningless. when n=4
When, printed 5
and 6
, we can infer that when we value the value greater than or equal to the size of the stream, there must be nothing left, and it must be an empty stream for the stream. After testing, it was confirmedcount=0
。
that is skip(long n)
Method before skipping n
(non-negative) elements, returning the remaining stream, which may be empty.
3. limit()
limit(long maxsize)
We did the same:
public static void limit(long maxsize) {
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6);
integerStream.limit( maxsize).forEach(integer -> System.out.println("integer = " + integer));
}
when n < 0
When it was directly thrown out IllegalArgumentException
abnormal. when n=0
When, an empty stream is returned. when n=4
When, printed 1
、 2
、3
、 4
。 n=8
At the time, all elements were printed. feel like mysqThe pagination of the page has the same effect.
4. difference
Both methods intercept the stream. But there are some differences skip
Operations must always monitor the status of elements in the flow. To determine whether it needs to be discarded. so skip
It belongs to state operation.
and limit
We only care about whether we intercept its parameters maxsize
(Maximum interval value), nothing else cares. Once reached, the operation is interrupted immediately and returned to the flow. so limit
It belongs to an interrupt operation.
5. summary
Today's review of the Java Stream API skip()
andlimit()
Methods were discussed. I don't know what scenarios you will think of using them separately, so you might as well leave a message and let me know.
Comments0