Sort a List of Objects in Java


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


Is there any way to do it?

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


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

1 answer


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>() {
    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;
    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


Or in the opposite direction


Another Java8 gift for your faithful.

answered by 14.10.2016 в 13:47