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

com.jparams.store.index.reducer.ComparingReducer Maven / Gradle / Ivy

There is a newer version: 3.1.4
Show newest version
package com.jparams.store.index.reducer;

import java.util.Comparator;
import java.util.List;
import java.util.function.Function;

import com.jparams.store.index.Element;

abstract class ComparingReducer implements Reducer
{
    private final Function valueProvider;
    private final Comparator comparator;
    private final boolean nullGreater;

    @SuppressWarnings("unchecked")
    > ComparingReducer(final Function valueProvider, final boolean nullGreater)
    {
        this.valueProvider = valueProvider;
        this.comparator = Comparator.comparing(obj -> ((C) obj));
        this.nullGreater = nullGreater;
    }

    @SuppressWarnings("unchecked")
     ComparingReducer(final Function valueProvider, final Comparator comparator, final boolean nullGreater)
    {
        this.valueProvider = valueProvider;
        this.comparator = (Comparator) comparator;
        this.nullGreater = nullGreater;
    }

    @Override
    public void reduce(final K key, final List> elements)
    {
        elements.stream().reduce(this::reduce);
    }

    private Element reduce(final Element element1, final Element element2)
    {
        final Object comparable1 = valueProvider.apply(element1.get());
        final Object comparable2 = valueProvider.apply(element2.get());

        if (compare(comparable1, comparable2, comparator, nullGreater) > 0)
        {
            element2.remove();
            return element1;
        }

        element1.remove();
        return element2;
    }

    abstract int compare(Object value1, Object value2, Comparator comparator, boolean nullGreater);
}