Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to get n elements from a set

Tags:

java

java-8

set

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?

like image 808
Diaa Avatar asked Jun 29 '15 19:06

Diaa


People also ask

How do you find the nth element of a set?

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.

Does Set have get method?

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.

Can we convert Set to list in Java?

We can simply convert a Set into a List using the constructor of an ArrayList or LinkedList.


1 Answers

Similar to Steve Kuo's answer but also skipping the first x elements:

Iterables.limit(Iterables.skip(s, x), n);

Guava Iterables

like image 71
JamesB Avatar answered Oct 01 '22 16:10

JamesB