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

com.github.phantomthief.util.MorePredicates Maven / Gradle / Ivy

There is a newer version: 0.1.55
Show newest version
package com.github.phantomthief.util;

import static java.util.Collections.newSetFromMap;

import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * @author w.vela
 */
public final class MorePredicates {

    private MorePredicates() {
        throw new UnsupportedOperationException();
    }

    public static  Predicate not(Predicate predicate) {
        return t -> !predicate.test(t);
    }

    public static  Predicate applyOtherwise(Predicate predicate,
            Consumer negateConsumer) {
        return t -> {
            boolean result = predicate.test(t);
            if (!result) {
                negateConsumer.accept(t);
            }
            return result;
        };
    }

    public static  Predicate distinctUsing(Function mapper) {
        return new Predicate() {

            private final Set set = newSetFromMap(new ConcurrentHashMap<>());

            @Override
            public boolean test(T t) {
                return set.add(mapper.apply(t));
            }
        };
    }

    public static  Predicate afterElement(T element) {
        return afterElement(element, true);
    }

    public static  Predicate afterElement(T element, boolean inclusive) {
        return after(e -> Objects.equals(element, e), inclusive);
    }

    public static  Predicate after(Predicate predicate) {
        return after(predicate, true);
    }

    public static  Predicate after(Predicate predicate, boolean inclusive) {
        return new Predicate() {

            private boolean started;

            @Override
            public boolean test(T t) {
                if (started) {
                    return true;
                } else {
                    if (predicate.test(t)) {
                        started = true;
                        if (inclusive) {
                            return true;
                        }
                    }
                    return false;
                }
            }
        };
    }

    public static  Predicate probability(double probability) {
        return new Predicate() {

            private final Random random = new Random();

            @Override
            public boolean test(T t) {
                return random.nextDouble() < probability;
            }
        };
    }
}