Simplest solution
Just implement the java.lang.Comparable interface in your class, for example:
class MyStruct implements Comparable<MyStruct>{ public Boolean GUI; public float CallTime; public String ReqID; public String ReqGUID; public String Stereotype; public String StereotypeGUID; @Override public int compareTo(MyStruct other) { return ReqID.compareTo(other.ReqID); } @Override public String toString() { return "(" + ReqID + ")"; } }
Override print only toString () method.
Also, keep in mind that the String compareTo () method is sorted using lexicographic . If you need a numeric identifier, it is better to use int or another numeric type. Below is the full code for sorting using Arrays.sort (), as well as Collections.sort () - choose what suits you :)
public class MyStructSort { private final static String[] STRUCT_IDS = {"C", "D", "A", "Aa", "B", "Z", "Aaa" }; private static List<MyStruct> createList() { List<MyStruct> structList = new ArrayList<MyStruct>(); for (String id: STRUCT_IDS) { MyStruct struct = new MyStruct(); struct.ReqID = id; structList.add(struct); } return structList; } public static void main(String[] args) { List<MyStruct> dataList = createList(); Collections.sort(dataList); System.out.println("List sort:\t" + dataList); MyStruct[] dataArray = dataList.toArray(new MyStruct[dataList.size()]); Arrays.sort(dataArray);
This is just a demo code, so some null checks, getters and setters will be required to improve it.
source share