All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.intelie.pipes.ComparableAtom Maven / Gradle / Ivy

There is a newer version: 0.25.5
Show newest version
package net.intelie.pipes;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class ComparableAtom implements Comparable, Serializable {
    private static final long serialVersionUID = 1L;

    private final Object value;
    private final Comparable[] comparables;

    public ComparableAtom(Object value, Comparable... comparables) {
        this.value = value;
        this.comparables = comparables;
    }

    public static List extract(List atoms) {
        List list = new ArrayList();
        for (ComparableAtom atom : atoms) {
            list.add(atom.value());
        }
        return list;
    }

    public static ComparableAtom create(Object value, Scope scope, Object raw, Evaluable... sorters) {
        Comparable[] comparables = new Comparable[sorters.length];
        for (int i = 0; i < sorters.length; i++) {
            comparables[i] = sorters[i].eval(scope, raw);
        }
        return new ComparableAtom(value, comparables);
    }

    public Object value() {
        return value;
    }

    @Override
    public int compareTo(ComparableAtom that) {
        if (comparables.length != that.comparables.length)
            return comparables.length < that.comparables.length ? -1 : 1;

        for (int i = 0; i < comparables.length; i++) {
            int result = comparables[i] == null ?
                    that.comparables[i] == null ? 0 : -1 :
                    that.comparables[i] == null ? 1 : comparables[i].compareTo(that.comparables[i]);
            if (result != 0) return result;
        }

        return 0;
    }
}