Home > Software design >  Cannot convert from boolean to int inside a lambda function
Cannot convert from boolean to int inside a lambda function

Time:10-31

I have a lambda function inside .sort to use as a comparator to sort a list. What im trying to do:

List<Client> inDebt = new ArrayList<Client>(); // this is how inDebt isdefined
//code to fill indebt with Clients
inDebt.sort((c1,c2) -> c1.getAllDebts() > c2.getAllDebts());

c1 and c2 are Clients that have

private long Debt

as an atribute. I want to compare them and sort them from bigger debt to smaller debt in a one line function yet I'm getting this error:

incompatible types: bad return type in lambda expression
    boolean cannot be converted to int

Help?

CodePudding user response:

You can create a Comparator for a long getter method using built-in function of Comparator and which handles the specification of Comparator.compareTo:

inDebt.sort(Comparator.comparingLong(Client::getAllDebts));

CodePudding user response:

Just:

inDebt.sort(Comparator.comparing(Client::getAllDebts));

Obs: you can apply it sequentially in case want to order too for other fields. For example: ordering first for Debts long value, and the result of this for Loans long values. It will be:

        inDebt.sort(Comparator.comparing(Client::getAllLoans));
        inDebt.sort(Comparator.comparing(Client::getAllDebts));

//or: (yes, it is in reversal order!)
        inDebt.sort(Comparator.comparing(Client::getAllDebts)
                .thenComparing(Client::getAllLoans));
  • Related