[英]How can i optimize cycles?
有一種方法將 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.