有人可以帮助我优化下面的代码吗?我不想在同一列表上播放3次。我必须在同一列表上进行迭代并应用不同的映射功能。 有人可以提出任何更好的解决方案吗?
List<Dummy> dummy = getDummyData(); //Assume we are getting data from some source
List<NewDummy> newDummyList = dummy.stream().map(eachDummy -> mapper.map(eachDummy, NewDummy.class)).collect(Collectors.toList());
if(someCondition) {
final BigDecimal amount1 = dummy.stream().filter(eachDummy -> Optional.ofNullable(eachDummy.getAmount1()).isPresent())
.map(Dummy::getAmount1).reduce(BigDecimal.ZERO, BigDecimal::add);
final BigDecimal amount2 = dummy.stream().filter(eachDummy -> Optional.ofNullable(eachDummy.getAmount2()).isPresent())
.map(Dummy::getAmount2).reduce(BigDecimal.ZERO, BigDecimal::add);
return new DummyObject(newDummyList, amount1, amount2);
} else {
return new DummyObject(newDummyList);
}
答案 0 :(得分:6)
这似乎是自定义收集器的理想用例。但在此之前,我认为您可以按如下方式简化金额的总和:
BigDecimal amount1 = dummy.stream()
.map(Dummy::getAmount1)
.filter(Objects::nonNull)
.reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
现在,自定义收集器。您可以将Dummy
的实例累积到静态实用程序方法内的专用本地类的实例中:
static Collector<Dummy, ?, DummyObject> toDummyObject(
Function<Dummy, NewDummy> mapper,
boolean someCondition) {
class Accumulator {
List<NewDummy> newDummyList = new ArrayList<>();
BigDecimal amount1 = BigDecimal.ZERO;
BigDecimal amount2 = BigDecimal.ZERO;
public void add(Dummy dummy) {
newDummyList.add(mapper.apply(dummy));
}
public void addAndSum(Dummy dummy) {
if (dummy.getAmount1() != null) amount1 = amount1.add(dummy.getAmount1());
if (dummy.getAmount2() != null) amount2 = amount2.add(dummy.getAmount2());
add(dummy);
}
public Accumulator merge(Accumulator another) {
newDummyList.addAll(another.newDummyList);
return this;
}
public Accumulator mergeAndSum(Accumulator another) {
amount1 = amount1.add(another.amount1);
amount2 = amount2.add(another.amount2);
return merge(another);
}
public DummyObject finish() {
return someCondition ?
new DummyObject(newDummyList, amount1, amount2) :
new DummyObject(newDummyList);
}
}
return Collector.of(
Accumulator::new,
someCondition ? Accumulator::addAndSum : Accumulator::add,
someCondition ? Accumulator::mergeAndSum : Accumulator::merge,
Accumulator::finish);
}
现在我们准备出发:
dummy.stream().collect(toDummyObject(
eachDummy -> mapper.map(eachDummy, NewDummy.class),
someCondition));
答案 1 :(得分:4)
我同意Federico的观点,Collector
似乎是这里的最佳选择。
但是,我宁愿只执行一些通用的“构建模块”,而不是实施一个非常专业的Collector
,然后使用这些模块来< em>组成在给定情况下需要的Collector
。
假设:
interface Mapper<T> {
T map(Dummy dummy, Class<T> type);
}
这是使用我的解决方案时DummyObject
的结构的样子:
Collector<Dummy, ?, DummyObject> dummyObjectCollector = someCondition
? toDummyObjectWithSums(mapper)
: toDummyObjectWithoutSums(mapper);
return dummy.stream().collect(dummyObjectCollector);
这是我撰写特定于用例的Collector
的方式:
private static Collector<Dummy, ?, DummyObject> toDummyObjectWithoutSums(Mapper<NewDummy> mapper) {
return Collectors.collectingAndThen(toNewDummyList(mapper), DummyObject::new);
}
private static Collector<Dummy, ?, List<NewDummy>> toNewDummyList(Mapper<NewDummy> mapper) {
return Collectors.mapping(dummy -> mapper.map(dummy, NewDummy.class), Collectors.toList());
}
private static Collector<Dummy, ?, DummyObject> toDummyObjectWithSums(Mapper<NewDummy> mapper) {
return ExtraCollectors.collectingBoth(
toNewDummyList(mapper),
sumGroupCollector(),
(newDummyList, amountSumPair) -> new DummyObject(
newDummyList, amountSumPair.getAmountSum1(), amountSumPair.getAmountSum2()
)
);
}
private static Collector<Dummy, ?, AmountSumPair> sumGroupCollector() {
return ExtraCollectors.collectingBoth(
summingAmount(Dummy::getAmount1),
summingAmount(Dummy::getAmount2),
AmountSumPair::new
);
}
static Collector<Dummy, ?, BigDecimal> summingAmount(Function<Dummy, BigDecimal> getter) {
return Collectors.mapping(getter,
ExtraCollectors.filtering(Objects::nonNull,
ExtraCollectors.summingBigDecimal()
)
);
}
private static class AmountSumPair {
private final BigDecimal amountSum1;
private final BigDecimal amountSum2;
// constructor + getters
}
最后,我们介绍了通用的“构建块”(我将其放置在ExtraCollectors
类中):
summingBigDecimal
:很明显filtering
:也很明显(相当于Stream.filter
)collectingBoth
:这是最有趣的之一:
Collector
(都在T
上运行,但是返回不同的结果,即Collector<T, ?, R1>
和Collector<T, ?, R2>
)BiFunction<R1, R2, R>
将它们组合成一个Collector<T, ?, R>
这是ExtraCollectors
类:
final class ExtraCollectors {
static Collector<BigDecimal, ?, BigDecimal> summingBigDecimal() {
return Collectors.reducing(BigDecimal.ZERO, BigDecimal::add);
}
static <T, A, R> Collector<T, A, R> filtering(
Predicate<T> filter, Collector<T, A, R> downstream) {
return Collector.of(
downstream.supplier(),
(A acc, T t) -> {
if (filter.test(t)) {
downstream.accumulator().accept(acc, t);
}
},
downstream.combiner(),
downstream.finisher(),
downstream.characteristics().toArray(new Collector.Characteristics[0])
);
}
static <T, R1, R2, R> Collector<T, ?, R> collectingBoth(
Collector<T, ?, R1> collector1, Collector<T, ?, R2> collector2, BiFunction<R1, R2, R> biFinisher) {
return collectingBoth(new BiCollectorHandler<>(collector1, collector2), biFinisher);
}
// method needed to capture A1 and A2
private static <T, A1, R1, A2, R2, R> Collector<T, ?, R> collectingBoth(
BiCollectorHandler<T, A1, R1, A2, R2> biCollectorHandler, BiFunction<R1, R2, R> biFinisher) {
return Collector.<T, BiCollectorHandler<T, A1, R1, A2, R2>.BiAccumulator, R>of(
biCollectorHandler::newBiAccumulator,
BiCollectorHandler.BiAccumulator::accept,
BiCollectorHandler.BiAccumulator::combine,
biAccumulator -> biAccumulator.finish(biFinisher)
);
}
}
这是BiCollectorHandler
类(由ExtraCollectors.collectingBoth
内部使用):
final class BiCollectorHandler<T, A1, R1, A2, R2> {
private final Collector<T, A1, R1> collector1;
private final Collector<T, A2, R2> collector2;
BiCollectorHandler(Collector<T, A1, R1> collector1, Collector<T, A2, R2> collector2) {
this.collector1 = collector1;
this.collector2 = collector2;
}
BiAccumulator newBiAccumulator() {
return new BiAccumulator(collector1.supplier().get(), collector2.supplier().get());
}
final class BiAccumulator {
final A1 acc1;
final A2 acc2;
private BiAccumulator(A1 acc1, A2 acc2) {
this.acc1 = acc1;
this.acc2 = acc2;
}
void accept(T t) {
collector1.accumulator().accept(acc1, t);
collector2.accumulator().accept(acc2, t);
}
BiAccumulator combine(BiAccumulator other) {
A1 combined1 = collector1.combiner().apply(acc1, other.acc1);
A2 combined2 = collector2.combiner().apply(acc2, other.acc2);
return new BiAccumulator(combined1, combined2);
}
<R> R finish(BiFunction<R1, R2, R> biFinisher) {
R1 result1 = collector1.finisher().apply(acc1);
R2 result2 = collector2.finisher().apply(acc2);
return biFinisher.apply(result1, result2);
}
}
}