javapmml

How to read the y value from the FieldName, FieldValue results map?


I have built an org.jpmml.evaluator.Evaluator from a PMML file

Evaluator evaluator = new LoadingModelEvaluatorBuilder()
    .load(new File(fileNamePmml))
    .build();

and evaluated it on a map of FieldName, FieldValue:

Map<FieldName, ?> results = evaluator.evaluate(arguments);

I can see the result is correct by printing the results:

{y={result=432.0}}

Now I want to read the value from the results:

double y = (double) results.get("y");

But I get the error

Error:(58, 48) java: incompatible types: capture#1 of ? cannot be converted to double

Solution

  • There are two issues with your code.

    First, the keys of the results map are org.dmg.pmml.FieldName, not java.lang.String. You should be converting string keys to field name keys, otherwise all Map#get(Object) lookups will come back empty:

    Map<FieldName, ?> results = evaluator.evaluate(..);
    Object targetValue = results.get(FieldName.create("y"));
    

    Second, map values are java.lang.Object subclasses. You're attempting to force-cast them to a Java primitive double value, which may or may not succeed, depending on the model. A much better idea would be to cast the value to java.lang.Number, and invoke its Number#doubleValue() method to obtain a primitive value. Yes, it's tedious and verbose, but it's safe:

    Number targetValue = (Number)results.get(FieldName.create("y"));
    double y = targetValue.doubleValue();