I am trying to sort an ordered list with objects, but I am not sure how to do it. I am putting in objects with a population(integer) associated with it. How would I make a method to sort the list so that the object with the lowest population would be first, and the object with the highest population would be last.
            Asked
            
        
        
            Active
            
        
            Viewed 184 times
        
    1
            
            
        - 
                    Needs code. Most folks use `Arrays.sort()` or `Collections.sort()` – markspace Apr 05 '20 at 20:05
- 
                    Also, what version of Java are you using? – markspace Apr 05 '20 at 20:05
- 
                    https://stackoverflow.com/questions/5932720/how-to-sort-an-attribute-of-an-object-using-collections Found by Google "java sort by attribute" – markspace Apr 05 '20 at 20:06
- 
                    E.g. `cities.sort(Comparator.comparingInt(City::getPopulation))` – Andreas Apr 05 '20 at 20:21
1 Answers
1
            
            
        "For any class to support natural ordering, it should implement the Comparable interface and override it’s compareTo() method. It must return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object."
public class YourObject implements Comparable<YourObject> {
  int population;
  YourObject(int pop) {
    population = pop;
  }
  @Override
  public int compareTo(YourObject other) 
  {
      return this.population - other.population;
  }
}
then you can use Collections.sort(list) on your list
 
    
    
        Miłosz Tomkiel
        
- 125
- 8
- 
                    1Don't use subtraction to sort by `int` values. Use [`Integer.compare(int x, int y)`](https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#compare-int-int-). – Andreas Apr 05 '20 at 20:19
