lundi 3 septembre 2018

Implement configurable sort criterias

I need to be able to sort an object by multiple conditions, and these sorts need to be configurable from the application.properties file (as in it should be possible to specify in the file the sorts to apply and the order).

So in my design I created a comparator for each one of the sorts, and then an enum with a supplier such as:

public enum CarSort {
    ENGINE(CarEngineComparator::new), BRAND(CarBrandComparator::new);

    private final Supplier<Comparator<Car>> constructor;

    CarSort(Supplier<Comparator<Car>> constructor){
        this.constructor = constructor;
    }

    Comparator<Car> newComparator() {
        return constructor.get();
    }
}

With this design, I then would be able to load the sorts from a properties file:

myapp.cars.sorts=BRAND,ENGINE

And chain the sorts with something like:

    Stream<Comparator<Car>> comparators = sorts.stream().map(CarSort::newComparator);
    return comparators
            .reduce(Comparator::thenComparing)
            .map(comparator -> filteredCars.sorted((comparator.reversed())))
            .orElse(filteredCars)
            .collect(Collectors.toList());

The problem I have at the moment is that one of the comparators requires two parameters, so I don't think this solution holds anymore, but I can't think of any clean alternatives at the moment.

Do you know if it would be possible to adapt my current design to fit this requirement, or have any alternative viable solution?

Aucun commentaire:

Enregistrer un commentaire