Grichka Grichka - 1 month ago 5x
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 :


After, I need to sort etapes by distanceFromThePrevious.

How can I do this ?


You can implement this using java comparator.

After this



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>{
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.