Arpit
Arpit

Reputation: 601

Java 8: How to get element at an index from a Stream

I have a stream, I need to get the element at an index in this stream Basically, a fetch on the basis of index of element like in List list.get(index)

Upvotes: 3

Views: 2494

Answers (1)

Mariusz Lotko
Mariusz Lotko

Reputation: 384

There is a skip method that abandons access to first N elements https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#skip-long-

After that you can use limit(1) and you have just one element at specified index.

EDIT: After @Holger answer there's also a possibility to call

stream().skip(index).findFirst()

Upvotes: 5

Related Questions