Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first(with zero index) element from stream conditionally

I have following code:

Stream<String> lines = reader.lines();

If fist string equals "email" I want to remove first string from the Stream. For other strings from the stream I don't need this check.

How could I acheve it?

P.S.

Sure I can transform it to the list, then use old school for loop but further I need stream again.

like image 993
gstackoverflow Avatar asked Nov 25 '19 10:11

gstackoverflow


People also ask

How do I remove a particular element from a stream list?

Using Streams, we can apply lambda functions known as Predicates. To read more about Streams and Predicates, we have another article here. Internally, removeIf uses an Iterator to iterate over the list and match the elements using the predicate. We can now remove any matching elements from the list.

What is findFirst in Java Stream?

Stream findFirst() returns an Optional (a container object which may or may not contain a non-null value) describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned.

How do I find the first element of a stream?

To get the first element, you can directly use the findFirst() method. This will return the first element of the stream.


1 Answers

While the reader will be in an unspecified state after you constructed a stream of lines from it, it is in a well defined state before you do it.

So you can do

String firstLine = reader.readLine();
Stream<String> lines = reader.lines();
if(firstLine != null && !"email".equals(firstLine))
    lines = Stream.concat(Stream.of(firstLine), lines);

Which is the cleanest solution in my opinion. Note that this is not the same as Java 9’s dropWhile, which would drop more than one line if they match.

like image 182
Holger Avatar answered Oct 20 '22 16:10

Holger