Home > Blockchain >  Codingbat challenge: sumNumbers Stream API Solution
Codingbat challenge: sumNumbers Stream API Solution

Time:06-05

Given the task enter image description here

CodePudding user response:

You maniacs. Just to me snarky you can convert any function to a stream. Map/Reduce is a common pattern:

int s = Stream.of("abc123xyz").mapToInt(str->{
    int sum = 0;

    java.util.regex.Matcher matcher = java.util.regex.Pattern.compile("[0-9] ").matcher(str);
    while (matcher.find()) {
        sum  = Integer.parseInt(matcher.group());
    }

    return sum;
}).sum();
System.out.println(s);

CodePudding user response:

Yes.

String[] data = { "abc123xyz", "aa11b33", "7 11" };
  • \\D - Split on any but string of non digits
  • filter empty strings from the split
  • convert to an int and sum the values.
  • return an entry to show both string and sum (not needed but shows the association)
Arrays.stream(data).map(
        str -> new AbstractMap.SimpleEntry<String, Integer>(
                str,
                Arrays.stream(str.split("\\D "))
                        .filter(s -> !s.isBlank())
                        .mapToInt(Integer::parseInt).sum()))
        .forEach(e -> System.out.printf("%-10s -> %d%n",
                e.getKey(), e.getValue()));

Prints

abc123xyz  -> 123
aa11b33    -> 44
7 11       -> 18

If you just want the sum you can do the following:

public static int getSum(String str) {
    return Arrays.stream(str.split("\\D "))
                .filter(s -> !s.isBlank())
                .mapToInt(Integer::parseInt)
                .sum();
}

CodePudding user response:

To keep the stream implementation closer to your original solution you could still employ a Pattern and Matcher and then stream the Matcher's results.

public int sumNumbers(String s) {
    return Pattern.compile("\\d ").matcher(s).results()
        .collect(Collectors.summingInt(m -> Integer.valueOf(m.group())));
}

Output

123
44
18

Here is a link to test the code with the expected output:

https://www.jdoodle.com/iembed/v0/rRS

  • Related