0

I am trying to solve little easy exercises with streams and I was wondering which way is the most efficient way to get a stream out of an Person[] but taking every second object.

Person[] myarr = {person1, person2, person3, person4, person5};

The output stream should consist of the objects person1, person3, person5 Any good efficient ideas?

Naman
  • 27,789
  • 26
  • 218
  • 353
P_Maffay
  • 55
  • 7
  • 1
    Does this answer your question? [Is there a concise way to iterate over a stream with indices in Java 8?](https://stackoverflow.com/questions/18552005/is-there-a-concise-way-to-iterate-over-a-stream-with-indices-in-java-8) – Torben Jan 17 '20 at 12:16
  • The most efficient way is to write an ArraySpliterator that advances by N indices instead of one. The most simple way is to use an accompanying IntStream and filter out unwanted indicis, as suggested by @JB Nizet. – Torben Jan 17 '20 at 12:23
  • The expected output must have a pattern that is derivable mathematically for that which you forgot to mention in the question and then what you're looking for it to iterate over a stream with indices. – Naman Jan 17 '20 at 12:30
  • 1
    @Torben I don’t think that a custom Spliterator implementation gives a significant advantage over IntStream…map – Holger Jan 17 '20 at 13:19

1 Answers1

2
IntStream.range(0, myarr.length)
    .filter(i -> i % 2 == 0)
    .mapToObj(i -> myarr[i]);
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255