How can i optimize cycles?

Kzz xD :

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);
Terry :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=409432&siteId=1