如何将具有多个条件的多个 for 循环转换为 Java 8 Stream Filter

问题描述 投票:0回答:1

我仍然习惯在 Java 中使用流过滤器。我花了很长时间将这个传统的 for 循环转换为它,因为它有多个列表和多个条件。

    CarTypes type = CarTypes();
    String carVariant = type.isASedan();
    String carType = "Default";
    List<Cars> cars = new ArrayList<Cars>();

    List<Cars> oldCars = cars.stream()
            .filter(record -> record.getCarYear().equals("2000"))
            .collect(Collectors.toList());

    if (!oldCars.isEmpty()) {
        for (Cars oldCar : oldCars) {
            for (CarSpecs carspec : oldCars.getSpecs()){
                if (carspec.getCarName().equalsIgnoreCase("Toyota") 
                        && carSpec.getVariant().equalsIgnoreCase("Corolla")
                        || carSpec.getVariant().equalsIgnoreCase("Tacoma")) {
                    carVariant = carSpec.getVariant();
                    carType = Boolean.parseBoolean(type.isASedan()) ? "Corolla" : "Tacoma";
                }
            }
        }
    }
java for-loop filter java-8 java-stream
1个回答
0
投票

尝试以下操作。

我通常只是链接 filter 调用。

carVariant
    = cars.stream()
          .filter(record -> record.getCarYear().equals("2000"))
          .filter(x -> {
              CarSpecs carspec = x.getSpecs();
              return carspec.getCarName().equalsIgnoreCase("Toyota")
                  && carspec.getVariant().equalsIgnoreCase("Corolla")
                  || carspec.getVariant().equalsIgnoreCase("Tacoma");
          })
          .findFirst()
          .get()
          .getSpecs().getVariant();
carType = Boolean.parseBoolean(type.isASedan()) ? "Corolla" : "Tacoma";
© www.soinside.com 2019 - 2024. All rights reserved.