-1

Is There a java util method, or a short way to sort an Array of some type by an attribute of that type. I currently have an array of Choice type objects where each have a getText() method that returns the visual representation of the choice. I can make a long method that creates an array of the choices texts, sort them, get their ordered index and then order the choices by that index, but I surely think there is some kind of a shortcut.

Any Suggestions?

Sam
  • 2,398
  • 4
  • 25
  • 37

1 Answers1

4
Collections.sort(list, new Comparator<Choice>(){
 public int compare (Choise c1, Choice c2) {
   return c1.getText().compareTo(c2.getText());
 }
});

add check for null if necessary

you can move comparator to external class and use reflection to read custom field from any object. but this will make code less understandable

Penkov Vladimir
  • 921
  • 5
  • 10