2

我目前面临代码可读性问题。问题如下:

拥有三个对象

// initialization skipped, all of three could be null as result of their initalization
Object obj1;
Object obj2;
Object obj3;

我想从它们创建两个布尔值,如下所示:

// all are null
boolean bool1 = (obj1 == null && obj2 == null && obj3 == null); 

// any of them is null

boolean bool2 = (obj1 == null || obj2 == null || obj3 == null);

我知道 guava 提供了内置谓词,例如isNulland notNull

有没有办法实现满足这两个布尔值的自定义谓词?(假设该.apply(..)函数将采用 3 个参数)

4

3 回答 3

4

我不确定你想要什么,但答案很可能是:是的,但这没什么意义。

您可以使用

FluentIterable<Object> it =
    FluentIterable.from(Lists.newArrayList(obj1, obj2, obj3));

boolean allNull = it.allMatch(Predicates.isNull());
boolean anyNull = it.anyMatch(Predicates.isNull());

但请放心,它的可读性要低得多,而且比正常方式要慢得多。

于 2014-02-11T12:44:52.323 回答
0

显然,您坚持使用Predicates,这在您的用例中绝对没有意义。所以 maaartinus 的答案是正确的,但没有提供带有谓词的答案。这是一个带有谓词的解决方案。

Predicate<Iterable<?>> anyIsNull = new Predicate<Iterable<?>>() {
    @Override public boolean apply(Iterable<?> it) {
        return Iterables.any(it, Predicates.isNull());
    }
};

Predicate<Iterable<?>> allAreNull = new Predicate<Iterable<?>>() {
    @Override public boolean apply(Iterable<?> it) {
        return Iterables.all(it, Predicates.isNull());
    }
};

用法:

bool1 = anyIsNull.apply(Arrays.asList(obj1, obj2, obj3));
bool2 = allAreNull.apply(Arrays.asList(obj1, obj2, obj3));
于 2014-02-11T13:25:04.083 回答
0

在 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 最好让你的项目自己实现它并避免额外的依赖。

于 2018-12-11T13:19:26.063 回答