I have this list ["z", "1", "3", "x", "y", "00", "x", "y", "4"]
that I need to get the first Integer
element after the String 00
in this case 4
. I am using Java 8 streams but any other method is welcome. Here is my starter code
myList.stream()
// Remove any non-Integer characters
.filter((str) -> !"x".equals(str) && !"y".equals(str) && !"z".equals(str))
.findFirst()
.orElse("");
That starts me off by removing all non-Integer Strings but gives me 1
. Now what I need is to get 4
which is the first element after 00
. What should I add to the filter?
Got from the comment.
String result = myList.stream().skip(myList.indexOf("00") + 1)
.filter((str) -> !"x".equals(str) && !"y".equals(str) && !"z".equals(str))
.findFirst()
.orElse("");
A simple for loop, perhaps. A lot more readable then a stream expression, also more general, since strings like 'x' and 'y' are not hard coded into it.
boolean found00 = false;
int intAfter00 = -1;
for(String str: myList) {
if("00".equals(str)) {
found00 = true; //from this point we look for an integer
continue;
}
if(found00) { //looking for an integer
try {
intAfter00 = Integer.parseInt(str);
} catch(Exception e) {
continue; //this was not an integer
}
break;
}
}
//If intAfter00 is still -1 here then we did not found an integer after 00
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