Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of object by particular member inside the object/class

Tags:

java

arrays

Say I have a class that looks like this (get/set omited):

class InfoClass{

   String name;
   String place;
   double distance;

}

And I create an array of my class from within my main activity that looks like this:

InfoClass[3] myInfoClass;

myInfoClass[0].name = "venue one";
myInfoClass[0].place = "place one";
myInfoClass[0].distance = 11.23234;

myInfoClass[1].name = "venue two";
myInfoClass[1].place = "place two";
myInfoClass[1].distance = 9.2345643;

myInfoClass[2].name = "venue three";
myInfoClass[2].place = "place three";
myInfoClass[2].distance = 5.23432;

How can I sort my array (myInfoClass[]) so that it is ordered by the distance member? i.e in the above example the array would be reversed because element [2] has the smallest distance and element [0] has the greatest distance?

Is there some function I can add to my class to do this or some other way?

like image 867
brux Avatar asked Nov 30 '22 14:11

brux


2 Answers

this should work ..

    public static void main(String[] args){
    InfoClass[] dd = new InfoClass[3];

    Arrays.sort(dd, new Comparator<InfoClass>(){

        @Override
        public int compare(InfoClass arg0, InfoClass arg1) {
            // TODO Auto-generated method stub
            if(arg0.distance == arg1.distance){
                return 0;
            }else if(arg0.distance < arg1.distance){
                return -1;
            }else{
                return 1;
            }
        }
    });
}
like image 119
lhlmgr Avatar answered Dec 05 '22 05:12

lhlmgr


Modify your class and implement Comparable interface if you don't want to use Comparator its also preferable when by default you want to provide sorting to array/collection of your objects then go for Comparable

class InfoClass implements Comparable<InfoClass> {

String name;
String place;
double distance;

@Override
public int compareTo(InfoClass o) {
    return new Double(this.distance).compareTo(new Double(o.distance));
}

and then you can sort them

Arrays.sort(myInfoClass)
like image 26
amicngh Avatar answered Dec 05 '22 06:12

amicngh