Sort a List of Objects in Java

3

I have a list of my own Java objects, which need to be sorted by the property code of the object itself.

    List<Calle> listaDeCalles;
    Calle calle1 = new Calle();
    calle1.setCodigo("A4");
...

    listaDeCalles.add(calle1);
    listaDeCalles.add(calle2);
    listaDeCalles.add(calle3);

Is there any way to do it?

I know there is an option to do it with the Collections.sort :

 java.util.Collections.sort(listaDeCalles)

And do it with a Set:

Set<Calle> setDeCalles = new Set<Calle>();

But neither is viable because some methods like the equals and the compareTo have been previously overwritten. And also the idea is that it does not touch FOR ANYTHING the Street class or its parent class.

What would be ideal for this case would be that there exists a method which orders a list by the code property which is String ascending or descending.

    
asked by Ralsho 14.10.2016 в 13:24
source

1 answer

7

Your best option is to implement a Comparator (anonymous or not) and include it in the function Collections.sort

//Expresión lambda java8
Collections.sort(listaCalles, (o1, o2) -> o1.getCodigo().compareTo(o2.getCodigo()));

//Clase anónima
Collections.sort(listaCalles, new Comparator<Calle>() {
    @Override
    public int compare(Calle o1, Calle o2) {
        return o1.getCodigo().compareTo(o2.getCodigo());
    }
});

I used compareTo() as an example comparison function ...

For a parametrizable comparator I leave this code

class CalleComparatorByCodigo implements Comparator<Calle> {
    private boolean asc;
    CalleComparatorByCodigo(boolean asc) {
        this.asc = asc;
    }
    @Override
    public int compare(Calle o1, Calle o2) {
        int ret;
        if (asc) {
            ret = o1.getCodigo().compareTo(o2.getCodigo());
        } else {
            ret = o2.getCodigo().compareTo(o1.getCodigo());
        }
        return ret;
    }
}

You can use it like this:

Collections.sort(listaCalles, new CalleComparatorByCodigo(true));

EDIT: I edit to add another Java8 functionality that I have recently learned and that may also be useful for these cases

listaCalles.sort(Comparator.comparing(Calle::getCodigo));

Or in the opposite direction

listaCalles.sort(Comparator.comparing(Calle::getCodigo).reversed());

Another Java8 gift for your faithful.

    
answered by 14.10.2016 в 13:47