Primitive streams (original) (raw)

Kasper Nielsen kasperni at gmail.com
Fri Jan 4 03:14:09 PST 2013


On Sat, Dec 29, 2012 at 7:19 PM, Brian Goetz <brian.goetz at oracle.com> wrote:

you can't define sum() on Stream

you could if you defined some kind of java.lang.Addable interface similar to java.lang.Comparable.

public interface class Addable<T *extends* Addable> {

T add(T other);

default T addAll(Iterable iterable) {

    Iterator<T> i = iterable.iterator();

    T result = i.next();// must have at least one element

    *while* (i.hasNext()) {

        result = result.add(i.next());

    }

    *return* result;

}

}

You could then let BigInteger, Integer, String?, ComplexNumber, AtomicLong, .... implement it like this

public class Integer implements Comparable, Addable {

Integer add(Integer other) {

    *return* *new* Integer(i + other.i);

}


Integer addAll(Iterable< Integer > iterable) {

    Iterator< Integer > i = iterable.iterator();

    *int* result = i.next().i;

    *while* (i.hasNext()) {

        result += i.next().i;

    }

    *return* *new* Integer(result);

}

}

On Stream you could then have @throws ClassCastException if elements are not mutable addable @throws NullPointerException if encountering a null Optional sum();

It would be really useful especially when working with something like BigInteger and BigDecimal. Where the addAll() could speed up adding lots of BigIntegers considerable.

In a crazy world you could even use it to provide operator overloading of +.



More information about the lambda-libs-spec-observers mailing list