我将如何重写这个以使用lambda

时间:2016-06-10 11:48:52

标签: lambda java-8

我怎样才能重写以下内容以使用lambda而不是内部函数:

List<ExtraService> extraServices = product.getServices().getExtraService().stream()
            .map(new Function<com.novasol.bookingflow.api.entities.products.ExtraService, ExtraService>() {

                @Override
                public ExtraService apply(com.novasol.bookingflow.api.entities.products.ExtraService es) {
                    ExtraService extraService = new ExtraService();
                    extraService.setServiceId(es.getServiceID());
                    extraService.setPriceUnitCode(es.getPriceUnitCode().intValue());
                    extraService.setServiceGroup(es.getServiceGroup().intValue());
                    extraService.setMaxUnits(es.getMaxUnits().intValue());

                    return extraService;
                }

            }).collect(toList());

2 个答案:

答案 0 :(得分:3)

您有两种选择。

首先 - 在方法中声明一个函数

Function<com.novasol.bookingflow.api.entities.products.ExtraService, ExtraService> toService = es -> {
        ExtraService extraService = new ExtraService();
        extraService.setServiceId(es.getServiceId());
        extraService.setPriceUnitCode(es.getPriceUnitCode().intValue());
        extraService.setServiceGroup(es.getServiceGroup().intValue());
        extraService.setMaxUnits(es.getMaxUnits().intValue());
        return extraService;
    };

    List<ExtraService> extraServices = product.getServices().getExtraService()
            .stream()
            .map(toService)
            .collect(toList());

第二 - 声明一个新方法,它执行转换并使用方法引用

 private ExtraService toService(com.novasol.bookingflow.api.entities.products.ExtraService es) {
        ExtraService extraService = new ExtraService();
        extraService.setServiceId(es.getServiceId());
        extraService.setPriceUnitCode(es.getPriceUnitCode().intValue());
        extraService.setServiceGroup(es.getServiceGroup().intValue());
        extraService.setMaxUnits(es.getMaxUnits().intValue());
        return extraService;
}

public void yourCurrentMethod() {
        List<ExtraService> extraServices = product.getServices().getExtraService()
            .stream()
            .map(this::toService)
            .collect(toList());
     ...
}

答案 1 :(得分:1)

这样的东西
List<ExtraService> extraServices = product.getServices().getExtraService().stream()
        .map( es -> {
                ExtraService extraService = new ExtraService();
                extraService.setServiceId(es.getServiceID());
                extraService.setPriceUnitCode(es.getPriceUnitCode().intValue());
                extraService.setServiceGroup(es.getServiceGroup().intValue());
                extraService.setMaxUnits(es.getMaxUnits().intValue());

                return extraService;
            }

        ).collect(toList());