简体   繁体   English

如何优化周期?

[英]How can i optimize cycles?

There is a method that takes two parameters of type String [] as input and does filtering depending on what it received.有一种方法将 String [] 类型的两个参数作为输入,并根据接收到的内容进行过滤。

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方法 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);

Hello @Kzz you can remove both nested loop by updating your repository query using the IN SQL operator as such:您好@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM