Fastest way to get the first n elements of a List into an Array

后端 未结 5 1979
囚心锁ツ
囚心锁ツ 2020-12-30 20:51

What is the fastest way to get the first n elements of a list stored in an array?

Considering this as the scenario:

int n = 10;
ArrayList

        
5条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 21:09

    Assumption:

    list - List

    Using Java 8 Streams,

    • to get first N elements from a list into a list,

      List firstNElementsList = list.stream().limit(n).collect(Collectors.toList());

    • to get first N elements from a list into an Array,

      String[] firstNElementsArray = list.stream().limit(n).collect(Collectors.toList()).toArray(new String[n]);

提交回复
热议问题