0
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?

Zoe
  • 997
  • 4
  • 10
  • 19

3 Answers3

1

Create a Comparator that takes a key and sorts it by that field

Also See

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
0

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.)

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
0

-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);
Java Panter
  • 307
  • 2
  • 12