Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list of structs by an element of the struct in java

Tags:

java

sorting

I have a list of structs that I would like to sort according to a specific element of the struct:

private class myStruct {

    public Boolean GUI;
    public float CallTime;
    public String ReqID;
    public String ReqGUID;
    public String Stereotype;
    public String StereotypeGUID;

}

private List<myStruct> DataList = new ArrayList<myStruct>();

How could I sort DataList by the element "ReqID" without hardcoding it? Is there a possibility to use Arrays.sort()?

like image 925
user1679802 Avatar asked Sep 18 '12 09:09

user1679802


3 Answers

You should use a Comparator.

 class YourComparator implements Comparator<myStruct>{

         public int compare(myStruct s1, myStruct s2){
              //here comes the comparison logic
         }
 }

And then use this form of the sort() method:

 Arrays.sort(T[] arrayToSort, Comparator<T> yourComparator);

It's not very clear whether you use a collection or an array as the data structure.

In case you use a List, then use Collections.sort().

like image 194
Razvan Avatar answered Sep 25 '22 09:09

Razvan


For custom sorting you can implement the Comparable interface.

With this interface you create a method compareTo() which returns a negative number, 0 or a positive number. Based on the return code Collections.sort() can tell if the element has to be before or after another element.

A nice example how to use it can be found in this answer: java class implements comparable

like image 41
nkr Avatar answered Sep 25 '22 09:09

nkr


use the Comparator interface like this

public static void main(String[] args) {
    List<myStruct> DataList = new ArrayList<myStruct>();
    //ADD Objects to DataList here

    Collections.sort(DataList, new Comparator() {

        public int compare(Object o1, Object o2) {
            myStruct p1 = (myStruct) o1;
            myStruct p2 = (myStruct) o2;
            int ret = -1;
            //business logic here
            if (Integer.parseInt(p1.ReqGUID) == Integer.parseInt(p2.ReqGUID)) {
                ret = 0;
            } else if (Integer.parseInt(p1.ReqGUID) > Integer.parseInt(p2.ReqGUID)) {
                ret = 1;
            } else if (Integer.parseInt(p1.ReqGUID) < Integer.parseInt(p2.ReqGUID)) {
                ret = -1;
            }//end business logic
            return ret;
        }
    });

}

Here inside the Collections.sort() method I am implementing the Comparator interface and overriding the compare() method. This will actually sort your list based on the business logic you implemented inside the compare() method;

like image 29
MaVRoSCy Avatar answered Sep 24 '22 09:09

MaVRoSCy