java - 如何优化周期?

标签 java spring hibernate spring-boot

有一种方法将两个 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);

关于java - 如何优化周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61044666/

相关文章:

java - 子类继承基类构造函数,同时保持代码重用原则

java - 同步方法调用其他同步方法

android - 使用 Tomcat 服务器托管 android 和 web 应用程序打开太多连接

java - hibernate 错误

java - Hibernate:如果参与者之一只有最终字符串字段(类似于无状态),则一二一和多二一相等

java - Android SurfaceView 闪烁

java - 如何检查文件是否为二进制文件?

java - 无法理解 : "Scope ' session' is not active for the current thread"

java - 为什么我的 @Async Future<T> 会阻塞?

java - @Transactional 在 JUnit 测试中不回滚