javajava-streammethod-reference

Make multiple Java streams assign values more compact


I have similar lines of code

batchPrice1 = items.stream()
                   .map(CommodityItem::getTotalPrice1)
                   .reduce(ZERO, BigDecimal::add);
batchPrice2 = items.stream()
                   .map(CommodityItem::getTotalPrice2)
                   .reduce(ZERO, BigDecimal::add);
batchPrice3 = items.stream()
                   .map(CommodityItem::getTotalPrice3)
                   .reduce(ZERO, BigDecimal::add);

Can I make it more compact and less repetetive?

I want a single stream that do the job


Solution

  • I suggest extracting it to method like:

    batchPrice1 = sum(CommodityItem::getTotalPrice1);
    batchPrice2 = sum(CommodityItem::getTotalPrice2);
    batchPrice3 = sum(CommodityItem::getTotalPrice3);
    
    private BigDecimal sum(Function<CommidityItem, BigDecimal> mapper){
      return items.stream()
                       .map(mapper)
                       .reduce(ZERO, BigDecimal::add);
    }
    

    Or if you want just one iteration, it can be achieved by

    YouNameIt accumulator = new YouNameIt();
    items.forEach(item-> accumulator.accumulate(item));
    
    class YouNameIt{
        BigDecimal batchPrice1;//getters
        BigDecimal batchPrice2;
        BigDecimal batchPrice3;
    
        void accumulate(CommodityItem item){
            batchPrice1 += item.getTotalPrice1();
            batchPrice2+= item.getTotalPrice2();
            batchPrice3+= item.getTotalPrice2();
        }
    }