Reputation: 1178
I'm using java stream and I have a problem. I have this code:
clients.stream()
.map(Client::getDescription)
.map(x -> x.substring(x.lastIndexOf("_v")))
.map(x -> x.substring(2))
.mapToInt(Integer::parseInt)
.max()
.getAsInt();
The description for every client could be "John_abc_v1", "Bill_crce_v2", "Joe_ghhj_V3"... and I get the maximum, in this case 3... but the problem is that v could be lowercase or uppercase and I don't know how to resolve that, so this line is not working .map(x -> x.substring(x.lastIndexOf("_v")))
I get String index out of range -1
when "V" is uppercase. How can I resolve that? Any feedback will be apreciated.
Upvotes: 1
Views: 1618
Reputation: 140318
There are various approaches, these are just a few:
Lowercase the entire string, as suggested by Sweeper. This means the V
would be converted to v
, so you could find it with lastIndexOf
.
Use regex to replace the parts of the string you don't want, i.e. everything but the trailing digits:
.map(x -> x.replaceAll(".*(\\d+)$", "$1"))
It then doesn't matter about the case of the V
.
Write a little method which finds the trailing digits:
String trailingDigits(String x) {
int last = x.length();
while (last > 0 && Character.isDigit(x.charAt(last - 1)) {
--last;
}
return x.substring(last);
}
and call from your map:
.map(x -> trailingDigits(x))
Upvotes: 5