Steve Kuo
Steve Kuo

Reputation: 63104

Java library to get Nth element from a Collection or Iterable

I have a Collection and need to get the Nth element as returned by its Iterator. I know I can iterate while counting through its Iterator elements. Is there a third party library (Google Guava or Apache Commons) that does this?

Upvotes: 10

Views: 6542

Answers (3)

Reimeus
Reimeus

Reputation: 159844

Guava's Iterators.get can help

Advances iterator position + 1 times, returning the element at the positionth position.

Upvotes: 12

Steve Chambers
Steve Chambers

Reputation: 39424

An example of using Iterators.get(Iterator iterator, int position) to get the 3rd element in myCollection:

com.google.common.collect.Iterators.get(myCollection.iterator(), 3);

Have used the fully qualified name above in case it is needed, e.g. in Eclipse's Display view.

Upvotes: 0

G. Bach
G. Bach

Reputation: 3909

EDIT: Ignore this, read over part of the question.


You can go like so:

for(int counter = 0; counter < max; counter++) 
    current = iterator.next();

After that, current will be the max-th element of the order induced by the iterator.

Upvotes: 0

Related Questions