How to use lambda expressions in Comparator class in Java

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

On this Stackoverflow page, I found very useful information on using lambda expressions. How to compare objects across multiple fields

What made me think about creating a Compartor class as follows:

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 doesn't work, but how can I make it work?

Ps. I have to use the Comparator class.

+4
source share
3 answers

, - , :

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);        
    }    
}

rawtype Comparator<Foto> , .

+2

Comparator.comapring a Comparator - :

// 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);
+5

You can try this old fashioned approach:

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

        // width asc order
        if(foto1.getWidth() != foto2.getWidth())
            return foto1.getWidth() - foto2.getWidth();

        // height asc order
        if(foto1.getHeight() != foto2.getHeight())
            return foto1.getHeight() - foto2.getHeight();

        // name asc order
        return foto1.getName().compareTo(foto2.getName());            
    }    
}
+1
source

Source: https://habr.com/ru/post/1669453/


All Articles