Search code examples
javafunctional-programmingcomparator

Returning a Comparator from a Function in Java


Is it possible to return a Comparator from a java.util.function.Function in Java?

I tried this in the following (contrieved) example, but Eclipse tells me that there is a syntax error ("Syntax error on token "amountOfPages", delete this token"):

import java.util.Comparator;
import java.util.List;
import java.util.function.Function;

public class App 
{
    private record Book(Integer nrOfPages) {};
    
    static Function<Integer, Comparator<Book>> byHasExactAmountOfPages = Integer amountOfPages -> (Book book1, Book book2) -> 
    {
         if(book1.nrOfPages.equals(amountOfPages) && book2.nrOfPages.equals(amountOfPages))
         {
             return 0;
         }
         else if(!book1.nrOfPages.equals(amountOfPages) && !book2.nrOfPages.equals(amountOfPages))
         {
             return 0;
         }
         else if(book1.nrOfPages.equals(amountOfPages) && !book2.nrOfPages.equals(amountOfPages))
         {
             return -1;
         }
         else
         {
             return 1;
         }
    };
    
    public static void main(String[] args) 
    {
        List.of(new Book(1), new Book(2), new Book(3)).stream()
            .sorted(byHasExactAmountOfPages.apply(2))
            .forEach(System.out::print);
    }
}

Solution

  • You missed the brackets around argument:

       here                   and here
        ( Integer amountOfPages ) -> (Book book1, Book book2) -> ...