Truncate a list to a given number of elements

后端 未结 3 805
囚心锁ツ
囚心锁ツ 2020-12-07 17:24

What method truncates a list--for example to the first 100 elements--discarding the others (without iterating through individual elements)?

3条回答
  •  孤城傲影
    2020-12-07 17:45

    subList, as suggested in the other answers, is the first that comes to mind. I would also suggest a stream approach.

    source.stream().limit(10).collect(Collectors.toList()); // truncate to first 10 elements
    source.stream().skip(2).limit(5).collect(Collectors.toList()); // discards the first 2 elements and takes the next 5
    

提交回复
热议问题