Search code examples
javaguavaapache-commons-collection

One liner for getting a sublist from a Set


Is there a one-liner (maybe from Guava or Apache Collections) that gets a sublist from a set. Internally it should do something like this:

public <T> List<T> sublist(Set<T> set, int count) {
  Iterator<T> iterator = set.iterator();
  List<T> sublist = new LinkedList<T>();
  int pos = 0;
  while (iterator.hasNext() && pos++ < count) {
    sublist.add(iterator.next());
  }
  return sublist;
}

Obviously, if there are not enough elements it has to return as many as possible.


Solution

  • With Guava:

    return FluentIterable.from(set) 
      .limit(count)
      .toImmutableList();
    

    (Also, this won't actually iterate over the whole set, in contrast to most of these other solutions -- it'll actually only iterate through the first count elements and then stop.)