Creating subset of a Set in Java

Paul Taylor picture Paul Taylor · Oct 18, 2012 · Viewed 48.4k times · Source

I have a LinkedHashSet, i.e an ordered set. I'm trying to find a function to just return a subset of the set, i.e the first 20 elements of the set. I know I can do it by creating a new set and then populating using an iteration of the first set but I was hoping for something more succinct.

Also took a look at Google's Guava libraries, but couldn't see what I wanted.

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · Oct 18, 2012

In Guava:

Set<Integer> subset = ImmutableSet.copyOf(Iterables.limit(set, 20));

Note that Iterables.limit() is evaluated lazily, so only one extra collection is created.