为了账号安全,请及时绑定邮箱和手机立即绑定

将值分配给列表的最短代码

将值分配给列表的最短代码

慕仙森 2022-01-19 13:03:06
什么可能是最短的代码:public void update(final Product object, final Callback<Product> callback) {    if(object.getIsDayDependent()) {        Double priceDay0 = object.getSundayPrice();        Double priceDay1 = object.getMondayPrice();        Double priceDay2 = object.getTuesdayPrice();        Double priceDay3 = object.getWednesdayPrice();        Double priceDay4 = object.getThursdayPrice();        Double priceDay5 = object.getFridayPrice();        Double priceDay6 = object.getSaturdayPrice();        List<DayPrice> dayPrices = new LinkedList<>();        dayPrices.add(new DayPrice(0, priceDay0));        dayPrices.add(new DayPrice(1, priceDay1));        dayPrices.add(new DayPrice(2, priceDay2));        dayPrices.add(new DayPrice(3, priceDay3));        dayPrices.add(new DayPrice(4, priceDay4));        dayPrices.add(new DayPrice(5, priceDay5));        dayPrices.add(new DayPrice(6, priceDay6));        object.setDayDependent(dayPrices);    } else {        object.setPrice(null);        object.setDayDependent(new LinkedList<>());    }    callback.onSuccess(object);}
查看完整描述

2 回答

?
收到一只叮咚

TA贡献1821条经验 获得超4个赞

下面的代码并没有像减少语句数量那样最小化代码,但它也消除了不必要的变量:


if(object.getIsDayDependent()) {

    List<Double> prices = Arrays.asList(object.getSundayPrice(),

            object.getMondayPrice(),

            object.getTuesdayPrice(),

            object.getWednesdayPrice(),

            object.getThursdayPrice(),

            object.getFridayPrice(),

            object.getSaturdayPrice());


    object.setDayDependent(IntStream.range(0, 7)

            .mapToObj(i -> new DayPrice(i, prices.get(i)))

            .collect(Collectors.toCollection(LinkedList<Double>::new)));

} else {

    object.setPrice(null);

    object.setDayDependent(new LinkedList<>());

}


查看完整回答
反对 回复 2022-01-19
?
翻阅古今

TA贡献1780条经验 获得超5个赞

在不修改关联类(产品类)作为挑战的情况下,我为此拥有的最短代码是这样的:


        if(object.getIsDayDependent())) {

            Double priceDay0 = object.getSundayPrice();

            Double priceDay1 = object.getMondayPrice();

            Double priceDay2 = object.getTuesdayPrice();

            Double priceDay3 = object.getWednesdayPrice();

            Double priceDay4 = object.getThursdayPrice();

            Double priceDay5 = object.getFridayPrice();

            Double priceDay6 = object.getSaturdayPrice();

            object.setDayDependent(new LinkedList<>(Arrays.asList(

                    new DayPrice(0, priceDay0),

                    new DayPrice(1, priceDay1),

                    new DayPrice(2, priceDay2),

                    new DayPrice(3, priceDay3),

                    new DayPrice(4, priceDay4),

                    new DayPrice(5, priceDay5),

                    new DayPrice(6, priceDay6))));

        }

不多,但也许有人可以回答一些更聪明的方法。


查看完整回答
反对 回复 2022-01-19
  • 2 回答
  • 0 关注
  • 111 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信