java consumer 用法,Java 8-Consumer andThen的用法

I have below POC to use Java 8 feature.

I want to update DB after accept method. Is it good to go with andThen()? When is this method called? Who calls it?

What is the basic use of andThen() method? Looking at the docs was confusing.

public class StockTest {

public static void main(String[] args) {

List traders = new ArrayList<>();

Random random = new Random();

// Initializing trading a/c's.

for (int i = 0; i < 10; i++) {

Trader trader = new Trader((random.nextInt(100) + 1) * 3);

traders.add(trader);

}

// Display Trade accounts.

System.out.println("Before Bonus, Units are:");

for (Trader trader : traders) {

System.out.print(trader.getUnits() + "\t");

}

// Add bonus to each trader.

traders.forEach(new Consumer() {

@Override

public void accept(Trader trader) {

trader.updateBonus(2);

}

@Override

public Consumer andThen(Consumer super Trader> after)

{

System.out.println("In andThen");

return Consumer.super.andThen(after);

}

});

// Display Trade accounts after bonus applied..

System.out.println("\nAfter bonus:");

for (Trader trader : traders) {

System.out.print(trader.getUnits() + "\t");

}

}

}

class Trader {

private int units;

public Trader(int initialUnits) {

this.units = initialUnits;

}

public int getUnits() {

return units;

}

public void setUnits(int units) {

this.units = units;

}

public void updateBonus(int bonusUnits) {

this.units = this.units * bonusUnits;

}

}

Please help with some example or use cases to utilize this method

解决方案

In short andThen is used to chain consumers, so the input will go to first and second consumer, lke below:

Consumer consumer1 = new Consumer() {

@Override

public void accept(Trader trader) {

trader.updateBonus(2);

}};

Consumer consumer2 = new Consumer() {

@Override

public void accept(Trader trader) {

// do something

}};

// Add bonus to each trader.

traders.forEach(consumer1.andThen(consumer2));

So here the Trader will be passed to consumer1, then to consumer2 and so on.

You don't have to implement this method, or override it. When it comes to Consumers, implement only the accept.

andThen method is a helper tool to join consumers. Instead of passing the input to all of them in a loop.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值