Why there is no BooleanConsumer in Java 8?

后端 未结 3 1112
囚心锁ツ
囚心锁ツ 2021-02-05 00:04

I\'m afraid that this is somewhat a silly question.

Is there anybody can tell me why there is no BooleanConsumer opposite to BooleanSupplier?

Is the

3条回答
  •  心在旅途
    2021-02-05 00:28

    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 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");
        }
    }
    

    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).

    If you don't need stream support, you can still write and use a "BooleanConsumer" in order to provide a type for some behavior, put I would prefer to see a functional interface with a more specific and descriptive name.

提交回复
热议问题