Problem
I'm writing a simple Java program in which I have a TreeSet
which contains Comparable elements (it's a class that I've written myself). In a specific moment I need to take only the first k elements from it.
What I've done
Currently I've found two different solution for my problem:
- Using a simple method written by me; It copies the first k elements from the initial
TreeSet
; - Use Google Guava greatestOf method.
For the second option you need to call the method in this way:
Ordering.natural().greatestOf(mySet, 80))
But I think that it's useless to use this kind of invocation because the elements are already sorted. Am I wrong?
Question
I want to ask here which is a correct and, at the same time, efficient method to obtain a Collection
derived class which contains the first k elements of a TreeSet
?
Additional information
Java version: >= 7