I was trying to find the most elegant way to get the n elements from a set starting from x. What I concluded was using streams:
Set<T> s;
Set<T> subS = s.stream().skip(x).limit(n).collect(Collectors.toSet());
Is this the best way to do it this way? Are there any drawbacks?
Inside the set elements will be stores in sorted order i.e. Now, to access an element at nth index we need to create an iterator pointing to starting position and keep on increment the iterator till nth element is reached i.e.
Set would require extra code to be able to keep track of an order. Note that there is a Set implementation that does keep track of insertion order--LinkedHashSet--but it doesn't have a get() method.
We can simply convert a Set into a List using the constructor of an ArrayList or LinkedList.
Similar to Steve Kuo's answer but also skipping the first x elements:
Iterables.limit(Iterables.skip(s, x), n);
Guava Iterables
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With