英文:
How can i optimize cycles?
问题
这是要翻译的部分:
Method
@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;
}
Here
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++);
}
}
}
Method 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);
英文:
There is a method that takes two parameters of type String [] as input and does filtering depending on what it received.
Method
@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;
}
How can I change this code so that there are not so many iterations here:
Here
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++);
}
}
}
Method 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);
答案1
得分: 0
你好 @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);
请注意,以上为翻译后的代码部分。
英文:
Hello @Kzz you can remove both nested loop by updating your repository query using the IN
SQL operator as such:
@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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论