3

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)

8
  • 12
    skip(index).findFirst() Commented Sep 6, 2017 at 7:20
  • 1
    Although Holger is correct, do you really want to discard all other elements of the stream? Commented Sep 6, 2017 at 7:23
  • @Holger thank you, it worked :) Commented Sep 6, 2017 at 7:31
  • 2
    if you have a Stream that is not ordered (let's say the source is a Set) what would this index mean at all? Commented Sep 6, 2017 at 7:31
  • 3
    @Andreas: it skips them, which implies being not processed in this specific stream operation, but when the source is a collection, you can stream over it as often as you want. The use case has not been described sufficiently to determine whether it is useful or not. Commented Sep 6, 2017 at 7:39

1 Answer 1

5

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.