I have a POC to use the Java 8 feature.
I want to update the DB after the accept method. Is it good to go with andThen()? When is this method called? Who calls it?
What is the main use of the method andThen()? The look at the documents was confusing.
public class StockTest {
public static void main(String[] args) {
List<Trader> traders = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < 10; i++) {
Trader trader = new Trader((random.nextInt(100) + 1) * 3);
traders.add(trader);
}
System.out.println("Before Bonus, Units are:");
for (Trader trader : traders) {
System.out.print(trader.getUnits() + "\t");
}
traders.forEach(new Consumer<Trader>() {
@Override
public void accept(Trader trader) {
trader.updateBonus(2);
}
@Override
public Consumer<Trader> andThen(Consumer<? super Trader> after)
{
System.out.println("In andThen");
return Consumer.super.andThen(after);
}
});
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 an example or use cases to use this method.
source
share