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()
?
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()
.
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With