I have a stream of strings:
Stream<String> st = Arrays.stream(new String[]{"10", "20", "30", "40", "50"});
I want to convert them to integer and sum them up using the reduce
method. I'm using reduce in the following format:
int result = st.reduce(0, (a, b) -> a Integer.parseInt(b));
I get this error:
no suitable method found for reduce(int, (a, b) -> a [...]nt(b))
any hint about how can I rewrite the reduce method to make it work?
CodePudding user response:
You need to provide a combiner function as the third argument to make it work:
int sum = Arrays.stream(new String[]{"10", "20", "30", "40", "50"})
.reduce(0, (a, b)-> a Integer.parseInt(b), Integer::sum);
Otherwise you're getting the different flavor of reduce()
which is capable of produce the result of the same type as the type of elements in the stream.
And you don't need reduce()
, the better way:
int sum = Stream.of("10", "20", "30", "40", "50")
.mapToInt(Integer::parseInt)
.sum();
CodePudding user response:
I want to convert them to integer and sum them up using the reduce method. I am using reduce in the following format:
When converting to an IntStream
via Integer::parseInt
the reduce
method takes a form of an int
starting value and an IntBinaryOperator
. So the following will work.
String[] data ={"10", "20", "30", "40", "50"};
int sum = Arrays.stream(data)
.mapToInt(Integer::parseInt).reduce(0, (a,b)->(a b));
System.out.println(sum);
prints
150
And for your edification (and future requirements) you can do it like so.
int sum = Arrays.stream(data).mapToInt(Integer::parseInt).sum();
System.out.println(sum);
prints
150
CodePudding user response:
Instead of using reduce()
, I'd break it into two steps: Convert the strings to ints (As an IntStream
), and then sum them:
Stream.of("10", "20", "30", "40", "50").mapToInt(Integer::parseInt).sum()