Novice User
Novice User

Reputation: 3824

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.

Upvotes: 1

Views: 115

Answers (3)

Olivier Gr&#233;goire
Olivier Gr&#233;goire

Reputation: 35457

Using Java only:

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

Upvotes: 4

Louis Wasserman
Louis Wasserman

Reputation: 198171

ImmutableList.copyOf(Iterables.limit(sortedSet, 3));

That should be all you need -- Iterables.limit does the important part.

Upvotes: 3

maaartinus
maaartinus

Reputation: 46472

For three smallest elements you could use

Iterator<E> it = mySortedSet.iterator();
ArrayList<E> = Lists.newArrayList(it.next(), it.next(), it.next());

This looks pretty hacky as it depends on the evaluation order of the arguments (which is guaranteed in Java). It also blows when the set is smaller. I'm not really recommending it as I wrote it, but you get the idea.

However, when all you need is these three elements, you can use a PriorityQueue or Guava's Comparators.least(int, Comparator).

Upvotes: 1

Related Questions