Search code examples
drools

Search element in List in Drools


I have list of objects Person. Object Person contain list of objects Car. How i can select from list only thoose Person, who contain Car selected type. For exmplain: Car with brand "BMW". I don't know do it without for loop.

person[0].addCar(new Car("BMW"));
person[0].addCar(new Car("Ford"));

person[1].addCar(new Car("Ford"));
person[1].addCar(new Car("Ford"));
person[1].addCar(new Car("Ford"));

How i can return person[0] in drools-regulations.

My code doesn't work.

rule "HardDrool"
salience 100
when
    $world : World();

    $persons: Human(
        (name == "Yura"),
        (!cars.isEmpty()),
        (Car(name == "BMW") from getCars())
        ) from $world.getPersons()
then
    System.out.println($persons);

end

Solution

  • rule "HardDrool"
    when
      $world : World();
      $person: Human( name == "Yura", !cars.isEmpty() )
         from $world.getPersons()
      exists Car( name == "BMW" ) from $person.getCars())
    then
      System.out.println( $person );
    end
    

    This should fire once for each Human owning at least one BMW. If you want to see each BMW, omit the exists.