0
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);
        }

I want to simplify the above code using java stream API. Is that possible for replace the if, else if with java 8 approach?

2 Answers 2

1

The stream API is not a good choice to simplify your code. There are some parts in your code that you can modify them.

1- Not to need to check rule.getConditions() nullity.

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

2- Don't repeat yourself by this: ((ValueCondition) condition) instead you can define a variable for it and use it.

ValueCondition vCondition = (ValueCondition) condition;

3- Instead concatenating salesChannelDisplayNames declare a List<String> salesChannelNames = new ArrayList<>(); and add channelName into it.

salesChannelNames.add(salesChannel.getDisplayName());

at the end use String.join(",", salesChannelNames) to add , delimeter between them.

Sign up to request clarification or add additional context in comments.

Comments

0

This is a sample you can try out. I have tried to completely eliminate 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;
    };
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.