35

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.

jbduncan
  • 425
  • 9
  • 17
Paul Taylor
  • 13,411
  • 42
  • 184
  • 351

6 Answers6

40

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.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
28

In Java 8 you can do

mySet.stream()
   .skip(start) // the offset
   .limit(count) // how many items you want
   .collect(Collectors.toSet());
thiagoh
  • 7,098
  • 8
  • 51
  • 77
24

A solution using streams and collectors:

Set<Integer> subSet = set.stream()
    // .skip(10) // Use this to get elements later in the stream
    .limit(20)
    .collect(toCollection(LinkedHashSet::new));
    // You could also collect to something else 
    // with another collector like this: 
    // .collect(toList());

This assumes the following import:

import static java.util.stream.Collectors.toCollection;
Lii
  • 11,553
  • 8
  • 64
  • 88
18

You could do this:

Set<Integer> set = new LinkedHashSet<>();
for (int i = 0; i < 50; i++) {
   set.add(i);
}

List<Integer> list = new ArrayList<>(set);
Set<Integer> subSet = new LinkedHashSet<>(list.subList(0, 20));
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • THanks that look neat, except for the fact you have to create both another Set and an ArrayList but I can live with that. – Paul Taylor Oct 18 '12 at 19:35
  • 3
    To avoid a `IndexOutOfBoundsException` use `Math.min(list.size(), 20)` as 2nd parameter of `subList` in case of a dynamically filled list. – dtrunk Feb 25 '16 at 13:20
5

You can either use at first a SortedSet as the subSet method exists on it.

You can also add the content of your set to a List and use the subList method on it. But it depends on the amount of data stored in your Set as you would not want to duplicate an enormous volume of data.

Otherwise you should stay with the iteration over the Set as it will be more efficient.

Alex
  • 25,147
  • 6
  • 59
  • 55
2

Simple helper method (You can use it for Set or any other collection):

public static <T> List<T> listOf(final Collection<T> set, final int limit) {
    final List<T> list = new ArrayList<>(limit);

    final Iterator<T> i = set.iterator();
    for (int j = 0; j < limit && i.hasNext(); j++) {
        list.add(i.next());
    }

    return list;
}
user1079877
  • 9,008
  • 4
  • 43
  • 54