简体   繁体   中英

How to get a second element of a collection?

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!

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM