1

I have a Car class, each Car class has a list of Wheel class and each Wheel class has a integer field airPressure.

public class Car {
  private List<Wheel> wheels;
  public List<Wheel> getWheels() {
    return wheels;
  }
}

public class Wheel {
  private int airPressure;
  public int getAirPressure() {
    return airPressure;
  }
}

Now I have a list of Cars and I have to filter out all cars that have any wheels' air pressure larger than defaultValue. I'm filtering cars but I need to iterate through all wheels. Now I have code like this:

I have: List<Cars> cars, int defaultValue
List<Cars> filteredCars = cars.stream()
  .filter(car -> car.getWheels().get(0).getAirPressure() < defaultValue)
  .filter(car -> car.getWheels().get(1).getAirPressure() < defaultValue)
  .filter(car -> car.getWheels().get(2).getAirPressure() < defaultValue)
  ...

How to iterate wheels of each car when filtering cars?

1
  • Have a look at this howto page? Commented Aug 25, 2017 at 3:59

1 Answer 1

2

This will select only cars with all wheels' air pressure below defaultValue:

List<Car> filteredCars = cars.stream()
        .filter(car -> car.getWheels()
                .stream()
                .allMatch(wheel -> wheel.getAirPressure() < defaultValue))
        .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. Do you know what's the simplest way to find the max value of airPressure of all wheels of all cars?
cars.stream().map(Car::getWheels).flatMap(List::stream).mapToInt(Wheel::getAirPressure).max()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.