javasetsubsetlinkedhashset

Creating subset of a Set in Java


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.


Solution

  • 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.