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

com.github.strangepleasures.match.Match Maven / Gradle / Ivy

There is a newer version: 1.1.0
Show newest version
package com.github.strangepleasures.match;


import java.util.Objects;
import java.util.function.Predicate;


public final class Match {
    private Match() {
    }

    public static  R match(T value, MatchingFunction... actions) {
        for (MatchingFunction action : actions) {
            try {
                if (action.matches(value)) {
                    return (R) action.apply(value);
                }
            } catch (ClassCastException ignore) {
            }
        }
        return null;
    }

    public static  void match(T value, MatchingConsumer... actions) {
        for (MatchingConsumer action : actions) {
            try {
                if (action.matches(value)) {
                    action.accept(value);
                    return;
                }
            } catch (ClassCastException ignore) {
            }
        }
    }

    public static  MatchingConsumer on(Predicate filter, MatchingConsumer action) {
        return new MatchingConsumer() {
            @Override
            public boolean matches(Object value) {
                return MatchingConsumer.super.matches(value) && filter.test((T) value);
            }

            @Override
            public void accept(T value) {
                action.accept(value);
            }
        };
    }

    public static  MatchingFunction on(Predicate filter, MatchingFunction mapper) {
        return new MatchingFunction() {
            @Override
            public boolean matches(Object value) {
                return MatchingFunction.super.matches(value) && filter.test((T) value);
            }

            @Override
            public R apply(T value) {
                return mapper.apply(value);
            }
        };
    }

    public static  MatchingConsumer on(T expected, Runnable runnable) {
        return new MatchingConsumer() {
            @Override
            public boolean matches(Object value) {
                return Objects.equals(value, expected);
            }

            @Override
            public void accept(T value) {
                runnable.run();
            }
        };
    }


    public static  MatchingFunction on(T expected, RunnableSupplier supplier) {
        return new MatchingFunction() {
            @Override
            public boolean matches(Object value) {
                return Objects.equals(value, expected);
            }

            @Override
            public R apply(T t) {
                return supplier.get();
            }
        };
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy