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

net.jqwik.engine.properties.FeatureExtractor Maven / Gradle / Ivy

The newest version!
package net.jqwik.engine.properties;

import org.jspecify.annotations.*;

import java.util.*;
import java.util.function.*;

@FunctionalInterface
public interface FeatureExtractor extends Function {

	static  FeatureExtractor identity() {
		return t -> t;
	}

	default Object applySafe(T t) {
		try {
			return apply(t);
		} catch (NullPointerException npe) {
			return null;
		}
	}

	default boolean isUniqueIn(T value, Collection elements) {
		if (this == identity()) {
			return !elements.contains(value);
		}
		Object feature = applySafe(value);
		return elements.stream()
					   .map(this::applySafe)
					   .noneMatch(x -> Objects.equals(x, feature));
	}

	default boolean areUnique(Collection elements) {
		Set set = new HashSet<>();
		for (T x : elements) {
			if (!set.add(applySafe(x))) {
				return false;
			}
		}
		return true;
	}
}