如何使用Java 8的方法简化if-else条件语句。

huangapple go评论77阅读模式
英文:

How can I simplify if else using java 8 aproach

问题

public Pair<String, String> getSalesChannelDisplayData(DiscountRule rule, List<SalesChannelDto> allSalesChannels) {
    String salesChannelDisplayNames = "";
    Set<String> storeCodes = new HashSet<>();

    if (rule.getConditions() != null) {
        Set<String> salesChannelIds = rule.getConditions().stream()
                .filter(condition -> condition instanceof ValueCondition)
                .map(condition -> (ValueCondition) condition)
                .filter(valueCondition -> valueCondition.getField() == Field.SALES_CHANNEL)
                .flatMap(valueCondition -> {
                    if (valueCondition.getOperator().equals(Operator.IN)) {
                        return valueCondition.getValues().stream();
                    } else if (valueCondition.getOperator().equals(Operator.NOT_IN)) {
                        Set<String> excludedIds = valueCondition.getValues();
                        return allSalesChannels.stream()
                                .map(SalesChannelDto::getId)
                                .filter(id -> !excludedIds.contains(id));
                    } else {
                        return Stream.empty();
                    }
                })
                .collect(Collectors.toSet());

        salesChannelDisplayNames = salesChannelIds.stream()
                .map(salesChannelId -> {
                    SalesChannelDto salesChannel = allSalesChannels.stream()
                            .filter(s -> s.getId().equals(salesChannelId))
                            .findFirst()
                            .orElse(null);
                    if (salesChannel != null) {
                        storeCodes.add(salesChannel.getDefaultCountryCode());
                        return salesChannel.getDisplayName();
                    } else {
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .collect(Collectors.joining(", "));

        String salesChannelDefaultCountryCodes = String.join(", ", storeCodes);

        return new Pair<>(salesChannelDisplayNames, salesChannelDefaultCountryCodes);
    }

    return new Pair<>(salesChannelDisplayNames, "");
}

请注意,尽管使用了Java 8的Stream API来简化代码,但由于原始代码涉及多个条件和逻辑,相应的Stream操作也变得复杂。这可能会影响代码的可读性。

英文:
public Pair&lt;String, String&gt; getSalesChannelDisplayData(DiscountRule rule, List&lt;SalesChannelDto&gt; allSalesChannels) {
String salesChannelDisplayNames = &quot;&quot;;
String salesChannelDefaultCountryCodes = &quot;&quot;;
Set&lt;String&gt; storeCodes = new HashSet&lt;&gt;();
if(rule.getConditions() != null) {
for (Condition condition : rule.getConditions()) {
if (condition instanceof ValueCondition) {
if (((ValueCondition) condition).getField() == Field.SALES_CHANNEL) {
Set&lt;String&gt; salesChannelIds = new HashSet&lt;&gt;();
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-&gt; s.getId().equals(salesChannelId));
salesChannelDisplayNames += salesChannel.getDisplayName() + &quot;, &quot;;
storeCodes.add(salesChannel.getDefaultCountryCode());
}
}
}
}
if (salesChannelDisplayNames.length()&gt;1) {
salesChannelDisplayNames = salesChannelDisplayNames.substring(0,salesChannelDisplayNames.length()-2);
salesChannelDefaultCountryCodes = Joiner.on(&quot;, &quot;).join(storeCodes);
}
return new Pair&lt;&gt;(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?

答案1

得分: 1

1- 不需要检查 rule.getConditions() 是否为 null。

2- 不要重复使用 ((ValueCondition) condition),而是可以为其定义一个变量并使用它。

3- 不要将 salesChannelDisplayNames 连接起来,而是声明一个 List<String> salesChannelNames = new ArrayList<>(); 并将 _channelName_ 添加到其中。

最后,使用 String.join(",", salesChannelNames) 在它们之间添加,分隔符。

英文:

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&lt;String&gt; salesChannelNames = new ArrayList&lt;&gt;(); and add channelName into it.

salesChannelNames.add(salesChannel.getDisplayName());

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

答案2

得分: 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;
    };
}
英文:

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, &quot;Audi A8&quot;);
String category1 = &quot;car&quot;;
System.out.println(ProductProxy.getEnrichedProduct.apply(product1, category1).toString());
Product product2 = new Product(2, &quot;OnePlus 8 Pro&quot;);
String category2 = &quot;mobile&quot;;
System.out.println(ProductProxy.getEnrichedProduct.apply(product2, category2).toString());
Product product3 = new Product(3, &quot;Macbook Pro&quot;);
String category3 = &quot;laptop&quot;;
System.out.println(ProductProxy.getEnrichedProduct.apply(product3, category3).toString());
Product product4 = new Product(4, &quot;Emaar Palm Heights&quot;);
String category4 = &quot;home&quot;;
System.out.println(ProductProxy.getEnrichedProduct.apply(product4, category4).toString());
}
}
@AllArgsConstructor
@Data
class Product {
private int productId;
private String productName;
}
class ProductProxy {
static BiFunction&lt;Product, String, Product&gt; getEnrichedProduct = (inputProduct, category) -&gt; {
AtomicReference&lt;Product&gt; outputProduct = new AtomicReference&lt;&gt;();
Objects.requireNonNull(category, &quot;The category is null&quot;);
Predicate&lt;String&gt; checkIsCar = productCategory -&gt; productCategory.equalsIgnoreCase(&quot;car&quot;) ? true : false;
Predicate&lt;String&gt; checkIsMobile = productCategory -&gt; productCategory.equalsIgnoreCase(&quot;mobile&quot;) ? true : false;
Predicate&lt;String&gt; checkIsLaptop = productCategory -&gt; productCategory.equalsIgnoreCase(&quot;laptop&quot;) ? true : false;
Optional.ofNullable(category).filter(checkIsCar).map(input -&gt; ProductService.enrichProductForCar.apply(inputProduct)).map(Optional::of).ifPresent(returnedProduct -&gt; outputProduct.set(returnedProduct.get()));
Optional.ofNullable(category).filter(checkIsMobile).map(input -&gt; ProductService.enrichProductForMobile.apply(inputProduct)).map(Optional::of).ifPresent(returnedProduct -&gt; outputProduct.set(returnedProduct.get()));
Optional.ofNullable(category).filter(checkIsLaptop).map(input -&gt; ProductService.enrichProductForLaptop.apply(inputProduct)).map(Optional::of).ifPresent(returnedProduct -&gt; outputProduct.set(returnedProduct.get()));
Optional.ofNullable(outputProduct.get()).orElseThrow(() -&gt; new RuntimeException(&quot;This is not a valid category&quot;));
return outputProduct.get();
};
}
class ProductService {
static Function&lt;Product, Product&gt; enrichProductForCar = inputProduct -&gt; {
inputProduct.setProductName(inputProduct.getProductName() + &quot;:Car&quot;);
return inputProduct;
};
static Function&lt;Product, Product&gt; enrichProductForMobile = inputProduct -&gt; {
inputProduct.setProductName(inputProduct.getProductName() + &quot;:Mobile&quot;);
return inputProduct;
};
static Function&lt;Product, Product&gt; enrichProductForLaptop = inputProduct -&gt; {
inputProduct.setProductName(inputProduct.getProductName() + &quot;:Laptop&quot;);
return inputProduct;
};
}

huangapple
  • 本文由 发表于 2020年5月5日 17:22:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/61609811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定