Sort A list of objects in Java

I have a list of own java objects, which need to be sorted by the code property 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 this?

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

 java.util.Collections.sort(listaDeCalles)

And to do it with a Set:

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

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

What would be ideal for this case would be that there exists a method that sorts a list by the Code Property which is an ascending or descending String.

 4
Author: Alan, 2016-10-14

1 answers

Your best bet 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 have used compareTo() as an example comparison function...

For a parameterizable comparator I leave you 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 that may also be useful for these cases

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

Or in reverse

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

Other Java8 gift for your faithful.

 8
Author: Thiamath, 2016-12-07 09:32:55