TDRS TDRS - 1 year ago 57
Java Question

How can i convert a specific Comparator to a Lambda expression?

I have a list of management songs, so this is my criteria to sort now the songs. How can i "convert" this to a lambda expression?

gestionCancionList.sort(new Comparator<GestionCancion>() {
public int compare(GestionCancion t1, GestionCancion t2){
return t1.vecesQueSeRepite == t2.vecesQueSeRepite ?
: (int)(t2.vecesQueSeRepite - t1.vecesQueSeRepite);

Answer Source

Even simpler:

Comparator<GestionCancion> aName = (t1,t2) -> t1.vecesQueSeRepite == t2.vecesQueSeRepite ? 
            : (int)(t2.vecesQueSeRepite - t1.vecesQueSeRepite);

The parameter types are implied by the generic type of the Comparator.

Edit: it can be done even simpler that the above. The comparator does not need to be separately defined. The lambda expression can be passed immediately to the sort method. Also in that case the types of the parameters is implied by the generic type of your collection object. Hence:

gestionCancionList.sort((t1,t2) -> t1.vecesQueSeRepite == t2.vecesQueSeRepite ? 
            : (int)(t2.vecesQueSeRepite - t1.vecesQueSeRepite));