optaplanner

Is it possible to use a constraint stream collector (or something similar) without groupBy()?


I'm trying to model a constraint based on the sum of a field across all instances of one of my entities, but the collectors work in concert with groupBy(). I don't want the grouping, just the operator over all the instances. Something like:

constraintFactory
    .forEach(MeaningOfLife.class)
    .sum(MeaningOfLife::getValue) // obviously doesn't work
    .penalize(HardSoftScore.ONE_SOFT, totalMeaning -> totalMeaning != 42)
    .asConstraint("Meaning of life is always 42");

I may be modeling this incorrectly, i've worked around it for now by using an EasyScoreCalculator, but i'd like to move the logic to the preferred constraint stream approach.


Solution

  • The technically correct answer to the question as phrased is "No." But actually, it's kind-of a "Yes":

    constraintFactory.forEach(MeaningOfLife.class)
        .groupBy(sum(MeaningOfLife::getValue))
        .penalize(HardSoftScore.ONE_SOFT, totalMeaning -> totalMeaning != 42)
        .asConstraint("Meaning of life is always 42");