class People {
int height;
int weight;
}
List<People> list = new ArrayList<People> ();
I'd like to sort the list with field 'height' as the key.
Is there any predefined method that I can use? How can I set height as my key?
class People {
int height;
int weight;
}
List<People> list = new ArrayList<People> ();
I'd like to sort the list with field 'height' as the key.
Is there any predefined method that I can use? How can I set height as my key?
Create a Comparator that takes a key and sorts it by that field
Also See
You could make your class implement Comparable<People>, which creates what's called a natural order, but it doesn't seem intuitive that people are always "more" or "less" based on height. A better approach is probably to create a Comparator, which you can then use with Collections.sort to sort the list.
(As a note: It's customary in Java for the class name be the singular of what the class represents, so in your case, it would be more legible to name it Person instead.)
-In order to put some objects into a specific order usually it is recommended to use a Set from Java Collection Framework.And than u have 2 options:
Implement in the same class Comparable and override the method compareTo.
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
Implement in a new class the interface Comparator and override the compare method.
http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
In your case using Lists you can still do these too and than call the method .sort() From Collections.
class HightSort implements Comparator<People > {
public int compare(People one, People two) {
return one.hight-two.hight;
}
}
Collections.sort(list);