user6874810
user6874810

Reputation:

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>() {
        @Override
        public int compare(GestionCancion t1, GestionCancion t2){
            return t1.vecesQueSeRepite == t2.vecesQueSeRepite ?
                    t1.song.dameInterprete().compareTo(t2.song.dameInterprete())
                    : (int)(t2.vecesQueSeRepite - t1.vecesQueSeRepite);
        }
    }

Upvotes: 2

Views: 917

Answers (3)

Bohemian
Bohemian

Reputation: 424993

Use Comparator factory method with method references (where possible):

Comparator.<GestionCancion, Veces>comparing(gc -> gc.vecesQueSeRepite).reversed()
    .thenComparing(GestionCancion::dameInterprete);

Making your code then:

gestionCancionList.sort(
  Comparator.<GestionCancion, Veces>comparing(gc -> gc.vecesQueSeRepite).reversed()
   .thenComparing(GestionCancion::dameInterprete));

The trick is to apply the reversed() to keep the code neat.

Note that explicit typing of the lambda is required when accessing a field (you haven't shown us what type vecesQueSeRepite is; I assumed Veces - substitute the actual type as needed).

Upvotes: 3

Albert Waninge
Albert Waninge

Reputation: 357

Even simpler:

Comparator<GestionCancion> aName = (t1,t2) -> t1.vecesQueSeRepite == t2.vecesQueSeRepite ? 
            t1.song.dameInterprete().compareTo(t2.song.dameInterprete())
            : (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 ? 
            t1.song.dameInterprete().compareTo(t2.song.dameInterprete())
            : (int)(t2.vecesQueSeRepite - t1.vecesQueSeRepite));

Upvotes: 3

Raghuveer
Raghuveer

Reputation: 3057

Simple

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

An example here

Upvotes: 0

Related Questions