elvis
elvis

Reputation: 1178

How to use map for lowercase or uppercase in Java 8 Streams?

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

Answers (1)

Andy Turner
Andy Turner

Reputation: 140318

There are various approaches, these are just a few:

  1. Lowercase the entire string, as suggested by Sweeper. This means the V would be converted to v, so you could find it with lastIndexOf.

  2. 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.

  3. 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

Related Questions