在 vanilla Java 8 中易于实现:
/**
* Check that <b>at least one</b> of the provided objects is not null
*/
@SafeVarargs
public static <T>
boolean anyNotNull(T... objs)
{
return anySatisfy(Objects::nonNull, objs);
}
/**
* Check that <b>at least one</b> of the provided objects satisfies predicate
*/
@SafeVarargs
public static <T>
boolean anySatisfy(Predicate<T> predicate, T... objs)
{
return Arrays.stream(objs).anyMatch(predicate);
}
/**
* Check that <b>all</b> of the provided objects satisfies predicate
*/
@SafeVarargs
public static <T>
boolean allSatisfy(Predicate<T> predicate, T... objs)
{
return Arrays.stream(objs).allMatch(predicate);
}
//... other methods are left as an exercise for the reader
(查看@SaveVarargs 的内容和原因)
用法:
// all are null
final boolean allNulls1 = !anyNotNull(obj1, obj2, obj3);
final boolean allNulls2 = allSatisfy(Objects::isNull, obj1, obj2, obj3);
// any of them is null
final boolean hasNull = anySatisfy(Objects::isNull, obj1, obj2, obj3);
PS 新手程序员的一般注意事项。Guava 是一个很棒的库,但如果你只是因为一些小而简单的东西(比如这个,Strings.isNullOrEmpty
等等)而想要它,IMO 最好让你的项目自己实现它并避免额外的依赖。