5

I just want to get the first element of a java stream, remove it and get on with my life. How can I do this without making it overly complicated (like with forEach, casting or filter)?

Perry
  • 1,709
  • 1
  • 17
  • 25
  • A `Stream` is not an `Iterator`. (But it does have a `findFirst` method.) – Sotirios Delimanolis Dec 03 '14 at 15:53
  • There is `findFirst()` but this is a short-circuiting terminal operation. You won't be able to process the Stream after calling it. – Alexis C. Dec 03 '14 at 15:54
  • 5
    if you want to use the stream excluding the first element you can also `stream.skip(1).getOnWithYourLife();` – assylias Dec 03 '14 at 15:55
  • 1
    Streams do not remove or modify the input data. The concept of stream (or functional programming) is that every stream operation results in a new (immutable) dataset (output is a function of input). So whatever you do, you'll never modify the stream, you make a new one. Therefore, the closest to popping an element is stream filtering (e.g. skipping the the first). – zapl Dec 03 '14 at 16:14
  • As assylias said, skipping the first element is as easy as calling `skip(1)`. If you want to retrieve that value, you have to convert the `Stream` into an `Iterator`, or better `Spliterator`, get the first element from it and create a new `Stream` out of it. – Holger Dec 03 '14 at 16:56
  • you can do it like this : `persons.stream().findFirst().ifPresent(person -> persons.remove(person))`; – Oussama Zoghlami Dec 04 '14 at 09:26

0 Answers0