英文:
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<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?
答案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<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.
答案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, "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;
};
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论