Search code examples
drools

How to iterate over a list of String and change it in RHS in drools


My use case i want to iterate over a List of String and Change the entries that match with the condition in LHS

Here is the json

{
  "name":[
    "james",
    "harry",
    "potter",
    "james"
    ]
}

And Here is my drl

when        
    $names:Names($nameslist:name)
    $value:String()  from $nameslist
    Boolean(booleanValue == true) from $value == "james"
    then
    System.out.println("Pojo Welcome-------");
end

My requirement is i want to change list such that where name is james i want to chnage it into Peter. How should i do it?

Here is my pojo class

package pojo_Classes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"name"
})
public class Assignment1News {

@JsonProperty("name")
private List<String> name = null;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

@JsonProperty("name")
public List<String> getName() {
return name;
}

@JsonProperty("name")
public void setName(List<String> name) {
this.name = name;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}

My requirement is i want to change list such that where name is james i want to chnage it into Peter. How should i do it?


Solution

  • There is no point in avoiding a simple function (or static method) that does the simple work of updating the list.

    rule "james to peter"
    when        
    $names:Names($nlist:name contains "james")
    then
      modify( $names ){ setName( replace( $nlist, "james", "peter" ) ); }
    end