0

Есть метод который принимает на вход два параметра типа 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);

1 ответ 1

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

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.