RosettaCodeData/Task/Accumulator-factory/Java/accumulator-factory-2.java

28 lines
804 B
Java
Raw Permalink Normal View History

2018-06-22 20:57:24 +00:00
import java.util.function.UnaryOperator;
public class AccumulatorFactory {
public static UnaryOperator<Number> accumulator(Number sum0) {
// Allows sum[0] = ... inside lambda.
Number[] sum = { sum0 };
// Acts like n -> sum[0] += n, but chooses long or double.
// Converts weird types (like BigInteger) to double.
return n -> (longable(sum[0]) && longable(n)) ?
(sum[0] = sum[0].longValue() + n.longValue()) :
(sum[0] = sum[0].doubleValue() + n.doubleValue());
2017-09-23 10:01:46 +02:00
}
2018-06-22 20:57:24 +00:00
private static boolean longable(Number n) {
return n instanceof Byte || n instanceof Short ||
n instanceof Integer || n instanceof Long;
2017-09-23 10:01:46 +02:00
}
2013-04-10 14:58:50 -07:00
2017-09-23 10:01:46 +02:00
public static void main(String[] args) {
2018-06-22 20:57:24 +00:00
UnaryOperator<Number> x = accumulator(1);
x.apply(5);
accumulator(3);
System.out.println(x.apply(2.3));
2017-09-23 10:01:46 +02:00
}
2013-04-10 14:58:50 -07:00
}