Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use lambda expressions in a Comparator class in Java

I am fairly new to Java and now I have to create some Comparator classes.

On this Stackoverflow page I have found some really useful information about using lambda expressions. How to compare objects by multiple fields

Which made me thing about creating a Compartor class like this:

public class WidthComparator implements Comparator{
    @Override
    public int compare(Object t, Object t1) {
        Foto foto1 = (Foto)t;
        Foto foto2 = (Foto)t1;

        return Comparator.comparing(Foto::getWidth)
               .thenComparing(Foto::getHeight)
               .thenComparingInt(Foto::getName);
        }
    }    
}

so when I have a collection called fotosCollection, I would like to be able to do this:

fotosCollection.sort(new HoogteComparator());

This obviously does not work, but how could I get this to work?

Ps. I have to use a Comparator class.

like image 698
Johan Vergeer Avatar asked Feb 05 '23 02:02

Johan Vergeer


2 Answers

Comparator.comapring returns a Comparator - you can just use it directly:

// Define a "constant" comparator
private static final Comparator<Foo> HOOGTE_COMPARATOR = 
    Comparator.comparing(Foto::getWidth)
              .thenComparing(Foto::getHeight)
              .thenComparingInt(Foto::getName);

// Use it elsewhere in your code
fotosCollection.sort(HOOGTE_COMPARATOR);
like image 151
Mureinik Avatar answered Feb 07 '23 17:02

Mureinik


If you really don't want the comparator type to be anonymous for some reason, you can do:

public class WidthComparator implements Comparator<Foto>{
    private final static Comparator<Foto> FOTO_COMPARATOR = Comparator.comparing(Foto::getWidth)
        .thenComparing(Foto::getHeight)
        .thenComparingInt(Foto::getName);

    @Override
    public int compare(Foto foto1, Foto foto2) {    
        return FOTO_COMPARATOR.compare(foto1, foto2);        
    }    
}

I also would consider avoiding the use of the rawtype and implement Comparator<Foto> instead, as I did above.

like image 32
Calculator Avatar answered Feb 07 '23 17:02

Calculator