为什么Java 8中没有BooleanConsumer?

Jin*_*won 43 java function java-8

我担心这有点愚蠢的问题.

有没有人可以告诉我为什么没有BooleanConsumer相反的BooleanSupplier

除了"因为根本没有"之外还有其他原因吗?

我应该创建自己的吗?还是我错过了别的什么?

public interface BooleanConsumer {

    void accept(boolean value);

    default BooleanConsumer andThen(final BooleanConsumer after) {
        return v -> {
            accept(v);
            after.accept(v);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

更新

在哪里使用?我正在写一个使用大量消费者和供应商的图书馆.我成功写了一行,LongConsumer我遇到了一种情况,希望消费者接受一个来自方法结果的布尔值.说Files.deleteIfExist

Pet*_*rey 42

IntConsumer并且LongConsumer需要避免每个值的开销自动装箱.处理原始基元会更有效率.但是,对于布尔值和字节,每个可能的对象都被缓存,因此几乎没有理由避免使用Consumer<Boolean>Consumer<Byte>

  • 好吧,装箱和拆箱即使没有分配对象也增加了一些计算开销,并且对象也比基元需要更多的内存。此答案也不能解释为什么没有“ CharConsumer”。 (2认同)
  • Java中的@lbalazscs是转义分析的功能。与其在堆上分配对象,不如将其放置在堆栈上。这个词应该像锁定省略中那样被省略。 (2认同)
  • @lbalazscs 我相信原语消费者在那里支持一个 API,该 API 具有附加方法,如 sum、min、max (2认同)

Pau*_*ton 16

正如其他答案所表明没有很大的理由可以避免Consumer<Boolean>,但是没有很好的理由可以避免Supplier<Boolean>,因此需要另外的解释.

类似的问题是为什么你不能打开一个boolean值.答案是没有必要,因为你可以随时使用ifif else.

A BooleanConsumer实际上只不过是一个if else构造,因为a的accept()方法BooleanConsumer总是可以用这种形式编写:

if (v) {
    // Do something
} else {
    // Do something else
}
Run Code Online (Sandbox Code Playgroud)

如果你需要传递这样的代码作为数据,你可以传递一对Runnable代表"做某事"和"做其他事情"的代码.在许多情况下,您只需要其中一个,Runnable因为上面两个块中的一个是空的.

以同样的方式,不需要a BooleanPredicate因为它只不过是一对BooleanSuppliers而且不需要aa BooleanFunction<R>因为它只不过是一对Supplier<R>s.

与此相反,不可能将BooleanSupplier两个更简单的对象分解.

  • 但是你需要处理两个而不是一个.如果你只有一个会不会更方便?同样,为什么我们需要一个`BooleanSupplier`? (5认同)
  • 看起来有点牵强。 (2认同)

lba*_*scs 8

You can write your own BooleanConsumer, but in order to make it really useful, you would need to write your own BooleanStream, too. There is an IntStream, LongStream, and DoubleStream, but no "BooleanStream" (or "ShortStream", "FloatStream" etc). It seems that these primitives were judged not to be important enough.

You can always use Boolean objects instead of boolean primitives, and a Boolean Consumer to consume the values. Example code:

public class Main {
    public static void main(String[] args) {
        Consumer<Boolean> myConsumer = b -> System.out.println("b = " + b);

        Stream.of("aa", "bb", "cc")
                .map(Main::myBooleanFunction)
                .forEach(myConsumer);

    }

    static boolean myBooleanFunction(String s) {
        return s.startsWith("b");
    }
}
Run Code Online (Sandbox Code Playgroud)

myBooleanFunction returns a boolean, but using it in a map creates a stream of Booleans (because we are in the generic, non-primitive Stream. Again, we have mapToInt, mapToLong, mapToDouble to create an IntStream etc, but no mapToBoolean).

如果您不需要流支持,您仍然可以编写并使用"BooleanConsumer"以便为某些行为提供类型,我希望看到具有更具体和描述性名称的功能接口.