2

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?

funivan
  • 3,323
  • 1
  • 14
  • 19

3 Answers3

4

Since Cactoos 0.22 you can:

int sum = new SumOf(1, 2, 3).intValue();
yegor256
  • 102,010
  • 123
  • 446
  • 597
2

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.

gil.fernandes
  • 12,978
  • 5
  • 63
  • 76
0

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.

Januson
  • 4,533
  • 34
  • 42