I need to calculate sum of Iterable<Integer>
.
final Iterable<Integer> score = this.points()
final sum = new SumOfInts(...).value()
How can I do this using class SumOfInts
?
I need to calculate sum of Iterable<Integer>
.
final Iterable<Integer> score = this.points()
final sum = new SumOfInts(...).value()
How can I do this using class SumOfInts
?
If I understand your question correctly, you could sum the iterable using code similar to this example:;
final Iterable<Integer> score = Arrays.asList(1, 2, 3, 4);
Optional<Integer> sum = StreamSupport.stream(score.spliterator(), false).reduce((i1, i2) -> i1 + i2);
System.out.println(sum.get());
The printed result is:
10
Explanation:
Iterable can be converted to a spliterator and spliterator to stream. You can then perform reductions on the stream.
As soon as you have the stream you can solve the reduction in multiple ways.
Another alternative:
int summed = StreamSupport.stream(score.spliterator(), false).mapToInt(Integer::intValue).sum();
System.out.println(summed);
This is perhaps nicer, as you get rid of the Optional
result.
I couldn't find any examples of how to convert Integer
to Scalar<Number>
but since the Scalar
is an interface you can do something like this.
public long sum() throws Exception {
final List<Scalar<Number>> score = this.points()
.stream()
.map(this::toScalar)
.collect(Collectors.toList());
return new SumOfInts(score).value();
}
private Scalar<Number> toScalar(final Number number) {
return () -> number;
}
But I bet there is a better way.