org.agzamovr.collectors.SummingBigDecimalCollector Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of collectorex Show documentation
Show all versions of collectorex Show documentation
Java Collectors extensions for using with Java 8 streams
The newest version!
package org.agzamovr.collectors;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import static java.util.Comparator.nullsLast;
import static java.util.stream.Collectors.toList;
class SummingBigDecimalCollector {
static final SummingBigDecimalCollector SUMMING_BIG_DECIMAL_COLLECTOR = new SummingBigDecimalCollector();
private void validateInput(Function, BigDecimal> mapper,
Comparator> comparator,
Collector, ?, ?> downstream) {
Objects.requireNonNull(mapper, "Mapper cannot be null");
Objects.requireNonNull(comparator, "Comparator cannot be null");
Objects.requireNonNull(downstream, "Downstream collector cannot be null");
}
R summingBigDecimalFinisher(Function super T, BigDecimal> mapper,
Comparator super T> comparator,
List list,
Collector downstream) {
validateInput(mapper, comparator, downstream);
list.sort(comparator);
BigDecimal sum = BigDecimal.ZERO;
Supplier downstreamSupplier = downstream.supplier();
Function finisher = downstream.finisher();
BiConsumer downstreamAccumulator = downstream.accumulator();
A container = downstreamSupplier.get();
for (T item : list) {
sum = sum.add(mapper.apply(item));
downstreamAccumulator.accept(container, sum);
}
return finisher.apply(container);
}
>
Collector> summingBigDecimal(Function super T, BigDecimal> mapper) {
return summingBigDecimal(mapper, nullsLast(Comparator.naturalOrder()));
}
, R>
Collector summingBigDecimal(Function super T, BigDecimal> mapper,
Collector downstream) {
return summingBigDecimal(mapper, nullsLast(Comparator.naturalOrder()), downstream);
}
Collector> summingBigDecimal(Function super T, BigDecimal> mapper,
Comparator super T> comparator) {
return summingBigDecimal(mapper, comparator, toList());
}
Collector, R> summingBigDecimal(Function super T, BigDecimal> mapper,
Comparator super T> comparator,
Collector downstream) {
return Collector.of(ArrayList::new,
List::add,
CollectorEx::listCombiner,
(list) -> summingBigDecimalFinisher(mapper, comparator, list, downstream));
}
}