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>
Pau*_*ton 16
正如其他答案所表明没有很大的理由可以避免Consumer<Boolean>
,但是没有很好的理由可以避免Supplier<Boolean>
,因此需要另外的解释.
类似的问题是为什么你不能打开一个boolean
值.答案是没有必要,因为你可以随时使用if
或if 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
因为它只不过是一对BooleanSupplier
s而且不需要aa BooleanFunction<R>
因为它只不过是一对Supplier<R>
s.
与此相反,不可能将BooleanSupplier
两个更简单的对象分解.
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"以便为某些行为提供类型,我希望看到具有更具体和描述性名称的功能接口.
归档时间: |
|
查看次数: |
4796 次 |
最近记录: |