limit 方法会限制输出值个数,入参是限制的个数大小,demo 如下:

    1. public void testLimit(){
    2. List<String> beforeCodes = students.stream().map(StudentDTO::getCode).collect(Collectors
    3. log.info("TestLimit 限制之前学生的学号为 {}",JSON.toJSONString(beforeCodes));
    4. List<String> limitCodes = beforeCodes.stream()
    5. .limit(2L)
    6. .collect(Collectors.toList());
    7. log.info("TestLimit 限制最大限制 2 个学生的学号 {}",JSON.toJSONString(limitCodes));
    8. // 直接连起来写
    9. List<String> codes = students.stream()
    10. .map(StudentDTO::getCode)
    11. .limit(2L)
    12. .collect(Collectors.toList());
    13. log.info("TestLimit 限制最大限制 2 个学生的学号 {}",JSON.toJSONString(codes));
    14. }

    输出结果如下:
    image.png