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?
Sure I can transform it to the list, then use old school for loop but further I need stream again.
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.
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.
To get the first element, you can directly use the findFirst() method. This will return the first element of the stream.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With