Currently it's not very clear what exactly are you trying to achieve. I assume that you want to create some generic solution to validate all the array elements in the same manner and then specialize it for various element types.
To solve this I'd recommend the following. Make ArrayPredicate<T>
not the class, but another interface which extends Predicate<T[]>
and provide single abstract method which validates the array element. The whole interface may look like this:
import java.util.Arrays;
import java.util.function.Predicate;
@FunctionalInterface
public interface ArrayPredicate<T> extends Predicate<T[]> {
public boolean testElement(T t);
default public boolean test(T[] a) {
if (a == null || a.length == 0)
return false;
return Arrays.stream(a).allMatch(this::testElement);
}
}
After that you can define specific predicates like this:
public class NonNullArrayPredicate implements ArrayPredicate<Object> {
@Override
public boolean testElement(Object obj) {
return obj != null;
}
}
public class NonEmptyStringArrayPredicate implements ArrayPredicate<String> {
@Override
public boolean testElement(String str) {
return str != null && !str.isEmpty();
}
}
And so on. Though the Java-8 way would probably be to remove these classes at all and use lambdas:
ArrayPredicate<Object> nonNullObjectArrayPredicate = Objects::nonNull;
ArrayPredicate<String> nonEmptyStringArrayPredicate = str -> str != null && str.isEmpty();
An alternative and more functional solution would be to get rid of ArrayPredicate
at all and create single higher-order function instead which translates an element predicate to array predicate:
// In any suitable class
public static <T> Predicate<T[]> forArray(Predicate<T> elementPredicate) {
return a -> a != null && a.length != 0 &&
Arrays.stream(a).allMatch(elementPredicate);
};
}
This way you can create specific predicates like this:
Predicate<Object[]> nonNullObjectArrayPredicate = forArray(Objects::nonNull);
Predicate<String[]> nonEmptyStringArrayPredicate = forArray(
str -> str != null && str.isEmpty());
So you don't need to declare any new classes, just functions.