多个仓库库存扣减-简单算法

概述


在做电商项目的时候,会涉及到库存扣减的问题,稍微复杂的情况是,多仓库库存扣减,比如说:
仓库warehouse1有4件商品,warehouse2有3件商品,这个时候用户需要买7件商品,这样无论哪个仓库都不够扣减,
这种情况下,会使用多仓库库存扣减的逻辑,warehouse1和warehouse2两个仓库的库存之和是3+4=7,是足够扣减6件的。


简单代码


public class Stock {

    /**
     * 库存id
     */
    private Long stockId;

    /**
     * 剩余库存数量
     */
    private Integer leavingNum;

    /**
     * 仓库 
     */
    private String warehouse;

    public Integer getLeavingNum() {
        return leavingNum;
    }

    public void setLeavingNum(Integer leavingNum) {
        this.leavingNum = leavingNum;
    }

    public Long getStockId() {
        return stockId;
    }

    public void setStockId(Long stockId) {
        this.stockId = stockId;
    }

    public String getWarehouse() {
        return warehouse;
    }

    public void setWarehouse(String warehouse) {
        this.warehouse = warehouse;
    }

}

public class InvReduceTest {

    public static void main(String[] args) {
        List stockList = new ArrayList<>();
        Stock stock1 = new Stock();
        stock1.setStockId(1L);
        stock1.setLeavingNum(4);

        Stock stock2 = new Stock();
        stock2.setStockId(2L);
        stock2.setLeavingNum(3);

        stockList.add(stock1);
        stockList.add(stock2);

        LinkedHashMap stockIdNumMap = new LinkedHashMap<>();
        int needReduceSumNum = 6;

        for (Stock stock : stockList) {
            if (needReduceSumNum <= 0) {
                break;
            }

            int ocpNum = Math.min(stock.getLeavingNum(), needReduceSumNum); 
            needReduceSumNum = needReduceSumNum - ocpNum;
            stockIdNumMap.put(stock.getStockId(), ocpNum);
        }

        System.out.println(JSON.toJSONString(stockIdNumMap));
    }
}

由于是多个仓库进行库存扣减,所以需要算出每个仓库具体要扣减多少件,如上面的代码.

你可能感兴趣的:(互联网技术经验累积,#,JAVA)