-4

I have the following class.

class{
        String name;
        int marks;
};   

Now i have to sort the objects either alphabetically(names) or descending(marks),based on user input. How to write the comparator function for this. User will enter 'n' to sort using names and 'm' to sort using marks.

Souvik
  • 23
  • 6

1 Answers1

1

Create two Comparator<> one for names another for marks and based on your user input choose one and perform following.

Collections.sort(yourList, yourComparator);

See sort(List<T> list, Comparator<? super T> c))

public class YourFirstComparator implements Comparator<YourClass> {
    @Override
     public int compare(YourClass o1, YourClass o2) {
        // your logic to return 
        // -1 if o1 is small, 1 is o1 is greater, 0 if both are equals
        return  yourValue

    }
}
Sumit Singh
  • 15,743
  • 6
  • 59
  • 89