Как я могу упростить, если еще использовать java 8 aproach - PullRequest
0 голосов
/ 05 мая 2020
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 stream API. Возможно ли заменить if, else if на подход java 8?

Ответы [ 2 ]

1 голос
/ 05 мая 2020

Stream API - не лучший выбор для упрощения кода. В вашем коде есть некоторые части, которые вы можете изменить.

1- Не нужно проверять rule.getConditions() null.

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

2- Не повторяйте это: ((ValueCondition) condition) вместо этого вы можете определить для него переменную и использовать ее.

ValueCondition vCondition = (ValueCondition) condition;

3- Вместо конкатенации salesChannelDisplayNames объявите List<String> salesChannelNames = new ArrayList<>(); и добавьте в него channelName .

salesChannelNames.add(salesChannel.getDisplayName());

в конце используйте String.join(",", salesChannelNames), чтобы добавить , разделитель между ними.

0 голосов
/ 26 мая 2020

Это образец, который вы можете попробовать. Я попытался полностью исключить 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;
    };
}
...