Grichka Grichka - 3 months ago 11
Java Question

Sort A Java ArrayList<MyObject> by a propriety

I have this Object :

public class AdresseReponse {

private String nom;
private String numero;
private String rue;
private String codePostal;
private String ville;
private String region;
private String pays;
private Coordonnee coordonnees;
private double distanceFromThePrevious;
private int number;

// + all setters & getters
}


In a other class, I have an ArrayList :

ArrayList<AdresseReponse> etapes = new ArrayList<AdresseReponse>();


and this methode :

public void testSort( AdresseReponse depart, AdresseReponse etape ) throws IOException, _Exception {...}


In this method, I do :

etapes.add(etape);


After, I need to sort etapes by distanceFromThePrevious.

How can I do this ?

Answer

You can implement this using java comparator.

After this

etapes.add(etape);

add

Sorter sorter = new Sorter();
Collections.sort(etapes, sorter);

Here sorter is the custom comparator that must be implemented. And Sorter class (of which sorter is an instance) code goes something like this

class Sorter implements Comparator<AddressResponse>{
@Override
public int compare(AddressResponse a, AddressResponse b){
    if(a.getdistanceFromThePrevious() >= b.getdistanceFromThePrevious())
        return 1;
    else if(a.getdistanceFromThePrevious() < b.getdistanceFromThePrevious())
        return -1;
}

Hope this helps.