java lambda map 函数_lambda – Java8 stream.map在同一个流上输出不同的映射函数?

这似乎是自定义收集器的理想用例.但在此之前,我认为您可以简化金额的总和,如下所示:

BigDecimal amount1 = dummy.stream()

.map(Dummy::getAmount1)

.filter(Objects::nonNull)

.reduce(BigDecimal::add).orElse(BigDecimal.ZERO);

现在,自定义收藏家.您可以在静态实用程序方法中将Dummy的实例累积到专用本地类的实例中:

static Collector toDummyObject(

Function mapper,

boolean someCondition) {

class Accumulator {

List 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));

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值