java8函数式编程--- 代码重构,抽出方法

 真实开发中,类肯定很多,但是他们会执行相同的操作,如下

/**
     * 获取单位统计销售数据
     * @param query
     */
    private void getAllTypeSalesUnitMap(OrdersSalesStatQuery query) {
        List allTypeSalesUnitList = orderTimerService.listSlaveAllTypeOrdersStat(QueryType.UNIT, query);
        allTypeSalesUnitPieceMap = allTypeSalesUnitList.stream().filter(item -> item.getUnitName().equals("件")).collect(Collectors.toMap(AllTypeOrdersSalesUnitStat::getOrderType,v->v,(v1,v2) -> v1));
        allTypeSalesUnitPacketMap = allTypeSalesUnitList.stream().filter(item -> item.getUnitName().equals("包")).collect(Collectors.toMap(AllTypeOrdersSalesUnitStat::getOrderType,v->v,(v1,v2) -> v1));
    }

    /**
     * 获取dlt单位统计销售数据
     * @param dltQuery
     */
    private void getDltAllTypeSalesUnitMap(DltOrdersSalesStatQuery dltQuery) {
        List dltAllTypeSalesUnitList = dltOrderCoreService.listSlaveAllTypeOrdersStat(QueryType.UNIT, dltQuery);
        dltAllTypeSalesUnitPieceMap = dltAllTypeSalesUnitList.stream().filter(item -> item.getUnitName().equals("件")).collect(Collectors.toMap(DltAllTypeOrdersSalesUnitStat::getOrderType,v->v,(v1,v2) -> v1));
        dltAllTypeSalesUnitPacketMap = dltAllTypeSalesUnitList.stream().filter(item -> item.getUnitName().equals("包")).collect(Collectors.toMap(DltAllTypeOrdersSalesUnitStat::getOrderType,v->v,(v1,v2) -> v1));
    }

    /**
     * 获取单位统计销售退货数据
     * @param query
     */
    private void getAllTypeRefundUnitMap(OrdersSalesStatQuery query) {
        List allTypeRefundUnitList = orderTimerService.listSlaveAllTypeOrdersStat(QueryType.REFUND_UNIT, query);
        allTypeRefundUnitPieceMap = allTypeRefundUnitList.stream().filter(item -> item.getUnitName().equals("件")).collect(Collectors.toMap(AllTypeOrdersRefundUnitStat::getOrderType,v->v,(v1,v2) -> v1));
        allTypeRefundUnitPacketMap = allTypeRefundUnitList.stream().filter(item -> item.getUnitName().equals("包")).collect(Collectors.toMap(AllTypeOrdersRefundUnitStat::getOrderType,v->v,(v1,v2) -> v1));
    }

然后Idea 就提示我 duplicates 了,所以要重构一下

要抽成方法的代码:

list.stream().filter(item -> item.getUnitName().equals("包")).collect(Collectors.toMap(DltAllTypeOrdersRefundUnitStat::getOrderType,v->v,(v1,v2) -> v1));

用java8函数式编程来进行方法的抽取:

    private  Map unitListConvertToMap(List list, Predicate supplier1, Function supplier) {
        Map map = list.stream().filter(supplier1).collect(Collectors.toMap(supplier,v->v,(v1,v2) -> v1));
        return map;
    }

使用:

    private void getDltAllTypeRefundUnitMap(DltOrdersSalesStatQuery dltQuery) {
        List list = dltOrderCoreService.listSlaveAllTypeOrdersStat(QueryType.REFUND_UNIT, dltQuery);
        dltAllTypeRefundUnitPieceMap = this.unitListConvertToMap(list,item -> item.getUnitName().equals("件"),DltAllTypeOrdersRefundUnitStat::getOrderType);
        dltAllTypeRefundUnitPacketMap = this.unitListConvertToMap(list,item -> item.getUnitName().equals("包"),DltAllTypeOrdersRefundUnitStat::getOrderType);
    }

你可能感兴趣的:(java,java)