Upul Doluweera
Upul Doluweera

Reputation: 2326

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.

Upvotes: 6

Views: 1349

Answers (2)

ZhekaKozlov
ZhekaKozlov

Reputation: 39536

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

Upvotes: 8

Jack
Jack

Reputation: 133577

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

Upvotes: 5

Related Questions