【发布时间】:2020-06-19 12:21:36
【问题描述】:
我必须使用 Set 字符串过滤 Map 值,我可以让它工作(一位合作伙伴建议使用 anyMatch() 代替我在这里所做的,但我看不出如何) 我想知道你对这个算法有什么看法,如果可以改进它,也许使用另一个Stream 函数甚至contains() 方法,我也不确定我是否可以避免直接迭代Set(对于每个循环)。
ProductsResponse serviceResponse = (obtained from backend) ...;
Set<String> productIds = (some code to collect the strings from another API) ...;
//Here starts the filtering process
serviceResponse.setProducts(serviceResponse.getProducts().entrySet().stream()
.filter(product -> {
for (String productId: productIds) {
if (product.getKey().startsWith(productId)) {
return true;
}
}
return false;
}).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
重要提示:我使用Set过滤Map中的产品,Set中的字符串格式与Map,因此使用startsWith() 比较它们是安全的
更新 1:添加涉及的类定义。
class ProductsResponse() {
private Map<String, ProductResource> products;
}
class ProductResource () {
private String productId;
private String name;
private Double price;
}
【问题讨论】:
-
你能把周围的代码贴出来吗?值是什么类型?如此有限的信息很难提供帮助。
-
是的,当然,我错了,我认为这很清楚,我会在几分钟内上传更多代码,谢谢。
标签: java dictionary for-loop lambda set