    001    package com.hammurapi.eventbus;
    002
    003    import java.util.Comparator;
    004
    005    import com.hammurapi.extract.Predicate;
    006
    007    /**
    008     * Comparator to sort join predicates.
    009     * @author Pavel Vlasov
    010     *
    011     * @param <E>
    012     * @param <C>
    013     */
    014    public class PredicateCostCardinalityComparator<E,C> implements Comparator<Predicate<E,C>> {
    015
    016            @Override
    017            public int compare(Predicate<E, C> p1, Predicate<E, C> p2) {
    018                    // Predicates ordered by cost first - cheaper come before more expensive
    019                    double delta = p1.getCost() - p2.getCost();
    020                    if (delta < -Double.MIN_VALUE) {
    021                            return -1;
    022                    }
    023
    024                    if (delta > Double.MIN_VALUE) {
    025                            return 1;
    026                    }
    027
    028                    // Then by cardinality (smaller comes before greater)
    029                    // And then by first index.
    030                    int c1 = p1.parameterIndices().size();
    031                    int c2 = p2.parameterIndices().size();
    032                    if (c1!=c2) {
    033                            return c1 - c2;
    034                    }
    035
    036                    for (int i: p1.parameterIndices()) {
    037                            for (int j: p2.parameterIndices()) {
    038                                    if (i!=j) {
    039                                            return i-j;
    040                                    }
    041                            }
    042                    }
    043
    044                    return p1.hashCode() - p2.hashCode();
    045            }
    046
    047    }