Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Stream: Find first element after element

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?

like image 217
Kihats Avatar asked Dec 31 '22 05:12

Kihats


2 Answers

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("");
like image 120
Lebecca Avatar answered Jan 02 '23 18:01

Lebecca


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
like image 41
Gtomika Avatar answered Jan 02 '23 18:01

Gtomika