Reputation: 539
I have a collection Collection<RECOBeacon> recoBeacons
the first element is obtained by RECOBeacon first = recoBeacons.iterator().next();
but I am having trouble to obtain the second one. I tried RECOBeacon second = first.next();
and second = first.iterator().next()
but none of these worked. Does anybody know how to solve this problem?
Thanks!
Upvotes: 6
Views: 15839
Reputation: 2110
If you're on Java8 you can use a Stream:
RECOBeacon second = recoBeacons.stream().skip(1).findFirst().orElse(null);
The nice thing about this solution is that findFirst returns an Optional, so you don't have to do the hasNext checks like when using an iterator.
Also note that the Collection interface does not guarantee order, so getting the n-th element may yield unexpected results.
Upvotes: 15
Reputation: 4544
In addition to @Eran's answer, you usually use Iterator
s for iterating the whole collection. In your case, what would you do if you wanted to get the 3rd, 4th... element? Then you can use a loop with your iterator.
Iterator<RECOBeacon> iter = recoBeacons.iterator();
while(iter.hasNext()) {
RECOBeacon nextBeacon = iter.next();
// do something with nextBeacon
}
Here, hasNext()
will prevent your iterator from running into a NoSuchElementException
and causes to break out of the loop when it reached the end of your collection.
Upvotes: 0
Reputation: 393936
You must use the same iterator to fetch both the first and the second elements:
Iterator<RECOBeacon> iter = recoBeacons.iterator();
RECOBeacon first = iter.next();
RECOBeacon second = iter.next()
It would be better to call iter.hasNext()
before each call to iter.next()
, to avoid an exception when the Collection
has less than two elements.
Upvotes: 14