0

I would need some idea on how to sort a number column in Wrapper class.

Wrapper class list is received from Callout and not by querying any SoBject. So cannot use ASC/DESC.

Tried out comparable Interface - It works only for String.

Any example on how to refer elements during the bubble sort would help:

Wrapper class Field - SerialNumber (get ;set}

   for (integer i = 0 ; i <List.size() ; i++ ) {
       for ( j = 0 ; j<List.size() ; j++) {
          //HOW TO REFER TO THE FIELD WHILE COMPARISON
       }
   }
2

1 Answer 1

2

As Adrian Larson and Mark Pond mentioned, Comparable can work equally well for any data type.

Here is an example on how to implement it. If the member variable type is not String (in your case Integer), you have to write the comparison logic instead of the default String CompareTo method. Let's take the below example, there is Student Class having Name (String) and Age (Integer) variable. Now check the difference between two versions, where first one is using Name for comparison and Second one is for Age Comparison. Hope this helps.

Comparison based on Name

global class Student implements Comparable {
    global String StudentName {get;set;}    
    global Integer StudentAge {get; set;}

    global Student(String Name, Integer Age) {
        StudentName = Name;
        StudentAge = Age;
    }
    global Integer compareTo(Object ObjToCompare) {
        return StudentName.CompareTo(((Student)ObjToCompare).StudentName);
    }        
}

Comparison based on Age

global class Student implements Comparable {
    global String StudentName {get;set;}    
    global Integer StudentAge {get; set;}

    global Student(String Name, Integer Age) {
        StudentName = Name;
        StudentAge = Age;
    }
    global Integer compareTo(Object ObjToCompare) {
        Student compareToStud = (Student)ObjToCompare;
        if (StudentAge == compareToStud.StudentAge) return 0;
        if (StudentAge > compareToStud.StudentAge) return 1;
        return -1;
    }        
}

You can find more details in the below links.

1 - https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_comparable.htm

2 - https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_list_sorting_sobject.htm

3
  • Your answer would be much more relevant if you sorted based on age instead.
    – Adrian Larson
    Commented Feb 9, 2017 at 17:20
  • Yes it is there, the second code snippet compares the age.
    – Saroj Bera
    Commented Feb 9, 2017 at 17:55
  • Ah, I see it now. It's kind of buried but is indeed included.
    – Adrian Larson
    Commented Feb 9, 2017 at 17:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .