There is a raw text stored in an ArrayList. To clean away unwanted lines from the top, I need to find the index of a string containing a certain tag.
The tag is not a complete String, only a substring. This means I cannot use myArrayList.indexOf("start marker")
(indexOf only looks for complete strings)
I tried to put a counter on a stream, counting the Strings it processes until it finds the marker, but it is not working.
Using a for-loop i can find the index, but this is slow and ugly (also gave some memory errors).
Streaming the ArrayList through a filter, and having the stream return the String that contains the marker gives me the full String that I'm looking for. Having the full string enables the ArrayList.indexOf method.
All in all it works now, but I still want to know how to set a counter on a stream.
For-loop (works but ugly):
for(String s : myArrayList)
{
if(s.contains("marker text"))
{
break;
}
else counter++;
}
Finding the full string (decent work-around):
String markerText = myArrayList.stream().filter(s -> s.contains("marker text")).
findFirst().orElse("marker not found");
int x = myArrayList.indexOf(markerText);
This doesn't work:
int counter = 0;
myArrayList.stream().peek(counter++).
filter(s -> s.contains("marker text")).findFirst();
This does not compile as peek() refuses to operate on integer x.
I have also tried casting x as an AtomicInteger and calling the getAndIncrement() method. This does not work either.
I see a lot of similar topics, but they all use the foreach method. Can someone tell me what I'm doing wrong?
You could get the index in one line using
IntStream:Then work with it: