SHOW:
|
|
- or go back to the newest paste.
| 1 | package ch.claude_martin.foo; | |
| 2 | ||
| 3 | import java.util.Arrays; | |
| 4 | import java.util.function.BinaryOperator; | |
| 5 | ||
| 6 | public class SomeClass {
| |
| 7 | static class Binary {
| |
| 8 | ||
| 9 | public static Binary ZERO = new Binary(false); | |
| 10 | public static Binary ONE = new Binary(true); | |
| 11 | private final boolean value; | |
| 12 | ||
| 13 | private Binary(boolean value) {
| |
| 14 | this.value = value; | |
| 15 | } | |
| 16 | ||
| 17 | public static Binary of(boolean b) {
| |
| 18 | return b ? ONE : ZERO; | |
| 19 | } | |
| 20 | ||
| 21 | public Binary add(Binary b) {
| |
| 22 | return new Binary(b.get() || value); | |
| 23 | } | |
| 24 | ||
| 25 | public boolean get() {
| |
| 26 | return value; | |
| 27 | } | |
| 28 | ||
| 29 | @Override | |
| 30 | public String toString() {
| |
| 31 | return value ? "1" : "0"; | |
| 32 | } | |
| 33 | } | |
| 34 | ||
| 35 | public static void main(String[] args) {
| |
| 36 | Binary[] numbers = new Binary[] { Binary.ZERO, Binary.ZERO, Binary.ONE, Binary.ZERO };
| |
| 37 | System.out.println(sum(numbers, Binary.ZERO, Binary::add)); | |
| 38 | } | |
| 39 | ||
| 40 | public static <T> T sum(T[] array, T zero, BinaryOperator<T> accumulator) {
| |
| 41 | - | return Arrays.stream(array).reduce(zero, accumulator); |
| 41 | + | T result = zero; |
| 42 | for (T element : array) | |
| 43 | result = accumulator.apply(result, element); | |
| 44 | return result; | |
| 45 | } | |
| 46 | } |