With Java streams it is easy to find an element that matches a given property.
Such as:
String b = Stream.of("a1","b2","c3")
.filter(s -> s.matches("b.*"))
.findFirst().get();
System.out.println("b = " + b);
Produces:
b=b2
However often one wants a value or values right after a match, rather than the match itself. I only know how to do this with old fashion for loops.
String args[] = {"-a","1","-b","2","-c","3"};
String result = "";
for (int i = 0; i < args.length-1; i++) {
String arg = args[i];
if(arg.matches("-b.*")) {
result= args[i+1];
break;
}
}
System.out.println("result = " + result);
Which will produce:
result=2
Is there a clean way of doing this with Java 8 Streams? For example setting result to "2" given the array above and predicate s -> s.matches("-b.*")
.
If you can get the next value, it would also be useful to also be able to get a list/array of the next N values or all values until another predicate is matched such as s -> s.matches("-c.*")
.