One liner for getting a sublist from a Set

yegor256 picture yegor256 · Sep 19, 2012 · Viewed 12.3k times · Source

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.

Answer

Louis Wasserman picture Louis Wasserman · Sep 20, 2012

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