Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is no primitive BiConsumer in java 8?

I am new to Java 8 and I can't find any primitive BiConsumer (IntBiConsumer etc), However There is a ToIntBiFunction which is the primitive specialization of the BiFunction. Also there is a IntBinaryOperator which is identical to ToIntBiFunction.

BiConsumer<Integer,String> wrappedBiConsumer = (i,s) -> System.out.printf("Consume %d %s \n",i,s);
ToIntBiFunction<String,String> toIntFunction = (a,b) -> a.length()* b.length();
  1. Is there any reason why Oracle have not provided a IntBiConsumer with Java8 ?
  2. Why there is two interfaces like "IntBinaryOperator" and "ToIntBiFunction" instead having a one interface like "IntBiFunction" ? ( if they are there to serve different purposes, still both of them can be extended from the same parent IntBiFunction)

I am pretty sure they designed it that way with a good reason and pls let me understand it.

like image 406
Upul Doluweera Avatar asked Dec 10 '22 12:12

Upul Doluweera


2 Answers

Actually, there is an ObjIntConsumer in Java which is a partial int-specialization of BiConsumer. So, your first example can be rewritten as:

ObjIntConsumer<String> consumer = (s, i) -> System.out.printf("Consume %d %s%n", i, s);
like image 52
ZhekaKozlov Avatar answered Dec 21 '22 22:12

ZhekaKozlov


I don't see there's any specific reason behind excluding IntBiConsumer, it's a trivial @FunctionalInterface that you can easily implement if you need it. I guess that's the same reason for which we don't have TriFunction or TriConsumer interfaces.

Don't mix IntBinaryOperator with ToIntBiFunction. The first is a function of type (int, int) -> int while the latter is of the form (T, U) -> int. So the latter could at most be (Integer, Integer) -> int but this incurs in boxing of primitives inside objects which is far for performant. IntBinaryOperator, instead, keeps them unboxed, which is useful when you need more performance (and that can be the case with a binary int function).

like image 33
Jack Avatar answered Dec 21 '22 23:12

Jack