一、方法概述
limit 方法可以对流中数据进行截取
Stream<T> limit(long maxSize)
该方法接收一个 long 类型参数,代表截取最大值,如果 maxSize 大于流中元素总数,则实际截取的是流中所有元素
二、案例
public class StreamDemo {
public static void main(String[] args) {
List<Person> personList = Arrays.asList(
new Person(1, "大毛", 30, 175),
new Person(2, "二毛", 25, 170),
new Person(3, "三毛", 25, 170),
new Person(4, "小毛", 20, 163));
// 获取 Stream 流
Stream<Person> personStream = personList.stream();
// 截取前 2 个元素
personStream.limit(2).forEach(System.out::println);
}
}
三、测试结果