gpt4 book ai didi

java - 如何使用 java 8 stream api 更正编写代码?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:08:18 25 4
gpt4 key购买 nike

我正在学习 Java 8,我想用 java Stream 重写普通的 java 代码。何做得更好。我的代码:

public Set<Product> getProductsByFilter(Map<String, List<String>>filterParams) {

Set<Product> productsByBrand = new HashSet<Product>();
Set<Product> productsByCategory = new HashSet<Product>();
Set<String> criterias = filterParams.keySet();
if (criterias.contains("brand")) {
for (String brandName : filterParams.get("brand")) {
for (Product product : listOfProducts) {
if (brandName.equalsIgnoreCase(product.
getManufacturer())) {
productsByBrand.add(product);
}
}
}
}

if (criterias.contains("category")) {
for (String category : filterParams.get("category")) {
productsByCategory.addAll(this.
getProductsByCategory(category));
}
}
productsByCategory.retainAll(productsByBrand);
return productsByCategory;
}

我不知道如何在 if (criterias.contains("brand")) 中更正重新格式化代码。

最佳答案

如果代码有效,为什么要更改它? , 不过,这里有一个使用流 API 的解决方案:

public Set<Product> getProductsByFilter(Map<String, List<String>> filterParams) {

Set<Product> productsByBrand = filterParams.containsKey("brand") ?
filterParams.get("brand")
.stream()
.flatMap(brandName -> listOfProducts.stream()
.filter(product -> brandName.equalsIgnoreCase(product.getManufacturer())))
.collect(Collectors.toCollection(HashSet::new)) : new HashSet<>();

Set<Product> productsByCategory =
filterParams.containsKey("category") ?
filterParams.get("category")
.stream()
.flatMap(category -> this.getProductsByCategory(category).stream())
.collect(Collectors.toCollection(HashSet::new)) : new HashSet<>();

productsByCategory.retainAll(productsByBrand);
return productsByCategory;
}

或者按照@shmosel 的建议,您可以使用 getOrDefault 来避免三元运算符。 :

Set<Product> productsByBrand = 
filterParams.getOrDefault("brand", Collections.emptyList())
.stream()
.flatMap(brandName -> listOfProducts.stream()
.filter(product -> brandName.equalsIgnoreCase(product.getManufacturer())))
.collect(Collectors.toCollection(HashSet::new));

Set<Product> productsByCategory =
filterParams.getOrDefault("category", Collections.emptyList())
.stream()
.flatMap(category -> this.getProductsByCategory(category).stream())
.collect(Collectors.toCollection(HashSet::new));

关于java - 如何使用 java 8 stream api 更正编写代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50651580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com