Convert stream BigDecimal summing to JavaFX Property

I have a problem trying to convert a bigdecimal to ObjectProperty

public class LinePiece {

    private int idLine;
    private ObjectProperty<BigDecimal> qty = new SimpleObjectProperty<BigDecimal>(BigDecimal.ZERO);
    private ObjectProperty<BigDecimal> price = new SimpleObjectProperty<BigDecimal>(BigDecimal.ZERO);
    private ObjectProperty<BigDecimal> remise = new SimpleObjectProperty<BigDecimal>(BigDecimal.ZERO);
    private IntegerProperty tva = new SimpleIntegerProperty();
    private ObjectProperty<BigDecimal> subTotal = new SimpleObjectProperty<BigDecimal>(BigDecimal.ZERO);
// Getters and Setters
}

We have a set of items of type LinePiece

private Set<LinePiece> LinePieces = new HashSet<>();
  LinePieces .add(new LinePiece());
  LinePieces .add(new LinePiece());
  LinePieces .add(new LinePiece());

After implementing summing to the actual set:

BigDecimal sum = lineCommande.stream().map(LineCommande::getSubTotal)
                .reduce(BigDecimal.ZERO,BigDecimal::add);

I want to make sum observable, so i can listen for sum changes. How i can acheive this ?

Remark: I can't use ObservableList here because i'm using hibernate

 @OneToMany(mappedBy = "piece", fetch = FetchType.EAGER, orphanRemoval = true, cascade = CascadeType.ALL)
    private Set<LinePiece> LinePieces = new HashSet<>();

if there another solution using ObservableList please tell me.

1 answer

  • answered 2017-06-17 18:04 James_D

    Create an ObjectBinding<BigInteger> (which implements ObservableValue<BigInteger>):

    ObjectBinding<BigInteger> sum = new ObjectBinding<BigInteger>() {
        {
            lineCommande.stream().forEach(l -> bind(l.subTotalProperty()));
        }
    
        @Override
        protected BigInteger computeValue() {
            return lineCommande.stream().map(LineCommande::getSubTotal)
                    .reduce(BigDecimal.ZERO,BigDecimal::add);
        }
    };