Search code examples
javaperformancecollectionsguava

Create list of certain size in Java from SortedSet


I've a SortedSet of TreeSet implementation, which I often convert to list via new ArrayList<>(mySortedSet) and then do subList(myList, 3) or any other number of elements.

How can I avoid using the subList on the new list creating and only get the ArrayList of required elements from SortedSet in one go. Using Java 11 with Guava.


Solution

  • Using Java only:

    List<E> list = sortedSet.stream().limit(3).collect(Collectors.toList());