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

io.ultreia.java4all.bean.JavaBeanComparatorBuilder Maven / Gradle / Ivy

There is a newer version: 0.3.3
Show newest version
package io.ultreia.java4all.bean;

/*-
 * #%L
 * Java Beans extends by Ultreia.io
 * %%
 * Copyright (C) 2018 Ultreia.io
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * .
 * #L%
 */

import java.util.Comparator;
import java.util.function.Function;
import java.util.stream.Stream;

/**
 * Created by tchemit on 11/01/2018.
 *
 * @author Tony Chemit - [email protected]
 */
public interface JavaBeanComparatorBuilder {

    void addComparator(Comparator predicate);

    Comparator build();

    default Stream sort(Stream elements) {
        Comparator comparator = build();
        return comparator == null ? elements.sorted() : elements.sorted(comparator);
    }

    interface Query, P extends JavaBeanComparatorBuilder> {

        P parent();

        V getter(O element);

        default P sort() {
            return addComparator(Comparator.comparing(this::getter));
        }

        default P reservedSort() {
            return addComparator(Comparator.comparing(this::getter).reversed());
        }

        default P addComparator(Comparator comparator) {
            P parent = parent();
            parent.addComparator(comparator);
            return parent;
        }

    }

    class QuerySupport, P extends JavaBeanComparatorBuilder> implements Query {
        private final P parent;
        private final Function getter;

        protected QuerySupport(P parent, Function getter) {
            this.parent = parent;
            this.getter = getter;
        }

        @Override
        public P parent() {
            return parent;
        }

        @Override
        public V getter(O element) {
            return element == null ? null : getter.apply(element);
        }

    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy