Using BiFunction in place of a Comparator does not work

java bifunction example
difference between function and bifunction in java 8
java bifunction method reference
bifunction vs function java
which functional interface would you use for the following no parameters returns a value
java functional interface
binaryoperator java 8 example
jdk8 bifunction

While initializing collections like TreeMap, TreeSet, etc. We can add our custom comparator. The code looks something like:

Map<Integer, String> map1 = new TreeMap<>(new Comparator<Integer>() {
    public int compare(Integer x, Integer y) {
        return x-y;
    }
});

Now, we can make replace this anonymous implementation with a lambda expression. The code would look like:

Map<Integer, String> map2 = new TreeMap<>((x,y) -> x-y);

Java-8 allows you to store lambda expressions in a variable through functional interfaces. So, I modified the above code to the following:

BiFunction<Integer, Integer, Integer> myComparator = (x,y) -> x-y;
Map<Integer, String> map3 = new TreeMap<>(myComparator);

But this last attempt did not work! It gave the following error:

Cannot infer type arguments for TreeMap<>

Why did it fail to resolve types in the last example?

Note: To confirm that this is not an IDE bug, I performed a raw compile using javac and it still gave the same error.

Although the lambda expression seems the same, the BiFunction is not the Comparator therefore you cannot interchange them.

Comparator<Integer> comparator = (x,y) -> x - y;
Map<Integer, String> map3 = new TreeMap<>(comparator);

Let's take a look deeper into these interfaces and implement them using an anonymous class:

Comparator<Integer> comparator = new Comparator<Integer>() {
    @Override
    public int compare(Integer x, Integer y) {
        return x - y;
    }
};

BiFunction<Integer, Integer, Integer> biFun = new BiFunction<Integer, Integer, Integer>() {
    @Override
    public Integer apply(final Integer x, final Integer y) {
        return x - y;
    }
};

The difference is also the name of the method. TreeMap expects Comparator in its constructor because its internal implementation will call compare according to the contract with Comparator.

By the way, the BinaryOperator<T> results in the same lambda expression as well.

Java, The BiFunction Interface is a part of the java.util.function package The main advantage of using a BiFunction is that it allows us to use 2 Note: The function being passed as the argument should be of type Function and not BiFunction. This exception will be handled in the apply() function, instead of� Use is subject to license terms. Also see the documentation redistribution policy . Scripting on this page tracks web page traffic, but does not change the content in any way.

That is simply because the TreeMap constructor expects a Comparator<Integer> rather than a BiFunction.

With writing BiFunction<Integer, Integer, Integer> myComparator = ... you explicitly say to the compiler that the variable is of that type. This prevents the compiler from infering the type required to the TreeMap constructor. Since BiFunction is not a Comparator, nor a subclass of it, the compiler does not allow this.

BinaryOperator (Java Platform SE 8 ), This is a specialization of BiFunction for the case where the operands and the result are all of the same type. Methods inherited from interface java.util. function. BiFunction returns a value. We define the data type for it while declaring BiFunction. BiPredicate performs the defined operation and returns boolean value. Find the example for how to use these functional interfaces in our code. BiConsumer java.util.function.BiConsumer is a java 8 functional interface. BiConsumer does not return value.

Because It expects the Comparator and you have supplied the BiFunction. From Oracle Docs :

@FunctionalInterface
public interface Comparator<T>

A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.

Trying Out Lambda Expressions in the Eclipse IDE, Lambda expressions, also called closures, are a short-form replacement for Lambda expressions can be used only with interfaces that declare a single method. If a functional interface method does not specify any formal parameters, empty When a lambda expression is invoked, the code in the lambda body is run. If you place a comparator next to any container (such as a chest or a dispenser) so that the container is behind the comparator, a signal is produced proportional to how full the container is. For example, a full container provides a charge of 16 to connected comparators, and a container with a small number of items (but not 0) produces a

Comparators and Collectors - Modern Java Recipes [Book], Comparators and Collectors Java 8 enhances the Comparator interface with Problem. You want to sort objects. In many situations, instead of a List you might want a Map , where the keys are the It extends BiFunction and applies when both arguments to the function and the return value are all from the same class. Represents an operation upon two operands of the same type, producing a result of the same type as the operands. This is a specialization of BiFunction for the case where the operands and the result are all of the same type. This is a functional interface whose functional method is BiFunction.apply(Object, Object).

Java 8 BiFunction Examples, In Java 8, BiFunction is a functional interface; it takes two arguments and uses andThen() to chain it with a Function to convert the Double into� In most cases a comparator is implemented using a dedicated comparator IC, but op-amps may be used as an alternative. Comparator diagrams and op-amp diagrams use the same symbols. Figure 1 above shows a comparator circuit. Note first that the circuit does not use feedback.

10. Java Built-In Lambda Interfaces, Comparable . However, Java 8 contains new functional interfaces to work specifically with lambda But the problem is that we have to write an interface like that in each program that uses it (or IntToLongFunction instead of Function <Integer, Long> This interface inherits the default method of the BiFunction interface:. 3 Using BiFunction in place of a Comparator does not work Apr 12 '19 3 While drag over the absolute element, drag leave event has been trigger continuously Mar 11 '19 2 How to detect if multiple keys are being pressed at the same time in html using JavaScript May 15 '19

Comments
  • Couldn't you declare your lambda function as Comparator<Integer> myComparator = (x,y) -> x-y; instead of BiFunction? Since Comparator is explicitly the type the TreeMap constructor requires.
  • I get a "cannot resolve constructor ....".
  • @luk2302, which version of java are you using?
  • @khelwood that works!!. But unfortunately does not resolve the question.
  • Regardless of which logic you implement, stay away from using minus. There is Integer.compare(int,int) doing the right thing, but usually, when you end up comparing two int values, you can use either Comparator.naturalOrder(), Comparator.reverseOrder​(), Comparator.comparingInt​(…), or a combination of them.