One insert for receiving a subscriber from a set

Is there a one-line (possibly from Guava or Apache Collections) that gets a sublist from the set. Internally, he 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 should return as many as possible.

+5
source share
6 answers

With Guava:

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

(In addition, it will not actually iterate over the entire set, unlike most other solutions - in fact, it will only go through the first elements countand then stop.)

+15
source
(new LinkedList<Object>(mySet)).sublist(0, Math.min(count, mySet.size()))

: ( ) , ( undefined HashSet TreeSet s). , , .

+13

:

return (new LinkedList<T>(set)).subList(0, count);

, count set.

+6

TreeSet subSet:

, . fromElement toElement , , Exclusive toExclusive . , . , .

INTEGER:

TreeSet<Integer> t = new TreeSet<Integer>();
t.add(1);
t.add(2);
t.add(3);
t.add(4);
t.add(5);

System.out.println("Before SubSet:");

for(Integer s : t){
    System.out.println(s);
}

System.out.println("\nAfter SubSet:");


for(Integer s : t.subSet(2,false,5,true)){
    System.out.println(s);
}

:

Before SubSet:
1
2
3
4
5

After SubSet:
3
4
5

, , ArrayList, Set, subList.

System.out.println("\nAfter SubSet:");

t = new TreeSet(new ArrayList(t).subList(2, 5));

for(Integer s : t){
    System.out.println(s);
}
+4

Set<String> s = new HashSet<String>();
// add at least two items to the set 
Set<String> subSet = new HashSet(new ArrayList<String>(s).subList(1, 2));

1 2

+1

Without making a copy Setin advance, you can do (using Guava):

Lists.newLinkedList(Iterables.getFirst(Iterables.partition(mySet, count), ImmutableList.of()))

This is a real one LinkedListcontaining only (before) the first countelements, and not a view in a larger list.

0
source

All Articles