如果使用java 8的方法,我如何简化?

问题描述 投票:-1回答:1
public Pair<String, String> getSalesChannelDisplayData(DiscountRule rule, List<SalesChannelDto> allSalesChannels) {
        String salesChannelDisplayNames = "";
        String salesChannelDefaultCountryCodes = "";
        Set<String> storeCodes = new HashSet<>();
        if(rule.getConditions() != null) {
            for (Condition condition : rule.getConditions()) {
                if (condition instanceof ValueCondition) {
                    if (((ValueCondition) condition).getField() == Field.SALES_CHANNEL) {
                        Set<String> salesChannelIds = new HashSet<>();
                        if(((ValueCondition) condition).getOperator().equals(Operator.IN)){
                            salesChannelIds = ((ValueCondition) condition).getValues();
                        }else if (((ValueCondition) condition).getOperator().equals(Operator.NOT_IN)) {
                            salesChannelIds = allSalesChannels.stream().map(SalesChannelDto::getId).collect(Collectors.toSet());
                            salesChannelIds.removeAll(((ValueCondition) condition).getValues());
                        }
                        for (String salesChannelId : salesChannelIds) {
                            SalesChannelDto salesChannel = Beans.find(allSalesChannels, s-> s.getId().equals(salesChannelId));
                            salesChannelDisplayNames += salesChannel.getDisplayName() + ", ";
                            storeCodes.add(salesChannel.getDefaultCountryCode());
                        }
                    }
                }
            }
    if (salesChannelDisplayNames.length()>1) {
        salesChannelDisplayNames = salesChannelDisplayNames.substring(0,salesChannelDisplayNames.length()-2);
        salesChannelDefaultCountryCodes = Joiner.on(", ").join(storeCodes);
    }
    return new Pair<>(salesChannelDisplayNames, salesChannelDefaultCountryCodes);
        }

我想用java流API来简化上面的代码,是否可以用java 8的方法来替换if, else if?是否可以用java 8的方法来替换if, else if?

java java-8 stream
1个回答
1
投票

流API不是一个很好的选择,可以简化你的代码。在你的代码中,有一些部分你可以修改它们。

1- 不需要检查 rule.getConditions() 空性。

if(rule.getConditions() != null) {...}

2- 不要通过这个来重复自己。((ValueCondition) condition) 你可以为它定义一个变量并使用它.

ValueCondition vCondition = (ValueCondition) condition;

3- 与其说是连接 salesChannelDisplayNames 宣称 List<String> salesChannelNames = new ArrayList<>(); 并加 频道名称 入其中。

salesChannelNames.add(salesChannel.getDisplayName());

最后用 String.join(",", salesChannelNames) 添加 , 之间的分隔符。


0
投票

这是一个例子,你可以试一试。我已经尝试完全消除if-else。

public class FunctionalIfElse {
    public static void main(String[] args) {

        Product product1 = new Product(1, "Audi A8");
        String category1 = "car";
        System.out.println(ProductProxy.getEnrichedProduct.apply(product1, category1).toString());

        Product product2 = new Product(2, "OnePlus 8 Pro");
        String category2 = "mobile";
        System.out.println(ProductProxy.getEnrichedProduct.apply(product2, category2).toString());

        Product product3 = new Product(3, "Macbook Pro");
        String category3 = "laptop";
        System.out.println(ProductProxy.getEnrichedProduct.apply(product3, category3).toString());

        Product product4 = new Product(4, "Emaar Palm Heights");
        String category4 = "home";
        System.out.println(ProductProxy.getEnrichedProduct.apply(product4, category4).toString());


    }

}

@AllArgsConstructor
@Data
class Product {
    private int productId;
    private String productName;
}

class ProductProxy {
    static BiFunction<Product, String, Product> getEnrichedProduct = (inputProduct, category) -> {
        AtomicReference<Product> outputProduct = new AtomicReference<>();
        Objects.requireNonNull(category, "The category is null");

        Predicate<String> checkIsCar = productCategory -> productCategory.equalsIgnoreCase("car") ? true : false;
        Predicate<String> checkIsMobile = productCategory -> productCategory.equalsIgnoreCase("mobile") ? true : false;
        Predicate<String> checkIsLaptop = productCategory -> productCategory.equalsIgnoreCase("laptop") ? true : false;

        Optional.ofNullable(category).filter(checkIsCar).map(input -> ProductService.enrichProductForCar.apply(inputProduct)).map(Optional::of).ifPresent(returnedProduct -> outputProduct.set(returnedProduct.get()));
        Optional.ofNullable(category).filter(checkIsMobile).map(input -> ProductService.enrichProductForMobile.apply(inputProduct)).map(Optional::of).ifPresent(returnedProduct -> outputProduct.set(returnedProduct.get()));
        Optional.ofNullable(category).filter(checkIsLaptop).map(input -> ProductService.enrichProductForLaptop.apply(inputProduct)).map(Optional::of).ifPresent(returnedProduct -> outputProduct.set(returnedProduct.get()));

        Optional.ofNullable(outputProduct.get()).orElseThrow(() -> new RuntimeException("This is not a valid category"));

        return outputProduct.get();
    };

}

class ProductService {
    static Function<Product, Product> enrichProductForCar = inputProduct -> {
        inputProduct.setProductName(inputProduct.getProductName() + ":Car");
        return inputProduct;
    };
    static Function<Product, Product> enrichProductForMobile = inputProduct -> {
        inputProduct.setProductName(inputProduct.getProductName() + ":Mobile");
        return inputProduct;
    };
    static Function<Product, Product> enrichProductForLaptop = inputProduct -> {
        inputProduct.setProductName(inputProduct.getProductName() + ":Laptop");
        return inputProduct;
    };
}
© www.soinside.com 2019 - 2024. All rights reserved.