gpt4 book ai didi

java - 如何优化周期?

转载 作者:行者123 更新时间:2023-12-01 17:35:45 24 4
gpt4 key购买 nike

有一种方法将两个 String [] 类型的参数作为输入,并根据收到的内容进行过滤。

方法

 @Override
public List<Product> filter(String[] brands, String[] cpus) {
List<Product> products;
List<Product> toReturn = new ArrayList<>();
int i = 0;
if(brands != null && cpus != null){
for(String brand: brands){
for(String cpu: cpus){
products = productRepo.findAllByBrandAndCpu(brand, cpu);
toReturn.addAll(products);
System.out.println(i++);
}
}
}else{
if (brands != null){
for (String brand: brands) {
products = productRepo.findAllByBrand(brand);
toReturn.addAll(products);
}
}else if(cpus != null){
for (String cpu: cpus) {
products = productRepo.findAllByCpu(cpu);
toReturn.addAll(products);
}
}else{
return productRepo.findAll();
}
}
return toReturn;
}

如何更改此代码,以便这里没有那么多迭代:

这里

if(brands != null && cpus != null){
for(String brand: brands){
for(String cpu: cpus){
products = productRepo.findAllByBrandAndCpu(brand, cpu);
toReturn.addAll(products);
System.out.println(i++);
}
}
}

方法findAllByBrandAndCpu

@Query(value = "SELECT p FROM Product p where p.brand.name = ?1 and p.cpu.name = ?2")
List<Product> findAllByBrandAndCpu(String brandName, String cpuName);

最佳答案

您好@Kzz,您可以通过使用 IN SQL 运算符更新存储库查询来删除两个嵌套循环:

@Query(value = "SELECT p FROM Product p where p.brand.name IN ?1 and p.cpu.name IN ?2")
List<Product> findAllByBrandAndCpu(List<String> brands, List<String> cpus);

关于java - 如何优化周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61044666/

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