kaleeway kaleeway - 9 months ago 69
Java Question

Multiplying nth character in Java String by 2 using stream and reduce?

Trying to use Java streams and reduce for this piece of code

//get string as char array
char[] chars = ccNumber.toCharArray();
// build array list to store integer value of each char
List<Integer> multipliedChars = new ArrayList<>();
//get char values on even positions of the array, multiply them by two and add them to array list
for (int i = 1; i < chars.length; i+=2) {
multipliedChars.add((chars[i] * 2) / 10);
}


Java 8 version

return IntStream.range(0, ccNumber.length())
.filter(n -> n % 2 != 0)
.map(ccNumber::charAt)
.reduce(1 , (x) -> (x * 2) / 10)
.sum();


However it is complaining that my arguments in the reduce method are incompatible with what I am trying to do?

Any ideas how to fix?

Answer Source

Just use second map instead of reduce:

IntStream.range(0, str.length())
                .filter(n -> n % 2 != 0)
                .map(str::charAt)
                .map(x -> (x * 2) / 10)
                .sum()

according to javadocs reduction

reduce(
       0,
       (a, b) -> a + b)

The reduce operation takes two arguments:

identity: The identity element is both the initial value of the reduction and the default result if there are no elements in the

stream. In this example, the identity element is 0; this is the initial value of the sum of ages and the default value if no members exist in the collection roster.

accumulator: The accumulator function takes two parameters: a partial result of the reduction (in this example, the sum of all

processed integers so far) and the next element of the stream (in this example, an integer). It returns a new partial result. In this example, the accumulator function is a lambda expression that adds two Integer values and returns an Integer value:

(a, b) -> a + b