javadroolskiedrools-guvnor

How to check in drool whether a value does not exist in a given list?


For classes that look like this (pseudo-code):

class Student{String name;}

class Department{List<Student> students;}

Let's say there a three students with names "A", "B", and "C".

My requirement is to check whether student "A" does not exist in the list of students. If the student exists, then the rule should fail.

I tried using not and not exists, but the 'then' clause still got executed. But the expectation is that 'then' clause should not be executed.

studentDetails1: department.students;

  1. not (exists ( Student(name == "A") from studentDetails1))
  2. not (Student(name == "A") from studentDetails1)

Can someone please help here?


Solution

  • The rule you are trying to create should check if student A is not present in the list of students in department. According to me you can achieve this with the code mentioned below.

    import java.util.List;
    
    rule "Check if student A does not exist"
    when
        $department: Department($students: students)
        not (Student(name == "A") from $students)
    then
        // Rule passes if student A does not exist
        System.out.println("Student A does not exist in the department");
    end
    

    You cannot avoid the execution of then block if the condition you mentioned in when does not matches. So if you frame your condition in when smartly, then you are good to go.