David David - 2 months ago 6
Java Question

Sorting ArrayList<String> by an Integer parsed from each String from Highest-> Lowest?

For example's sake, I will say I have 10 Strings in an ArrayList which each represent a person's name and age:

David:43
John:10
Wilson:23
George:59
Pat:3
Tom:52
Sydney:32
Mohammed:72
Jay:34
Adam:18


We'll call this ArrayList "people"

They are all in my ArrayList. I am able to get the age by using

Integer.parseInt(people.get(index).split(":")[1]);


But I want to sort the ArrayList to print out the people from highest to lowest age. I was wondering if there is any way to do this. And if there is, are there more efficient ways to do it?

Answer

There is a much more efficient, legible, and scalable option. Use Objects. Java is an OO language, and a Person object that stores name and age and implements Comparable to allow comparison between your objects solves your problem perfectly. Use the CompareTo method to define how your objects should be compared. For example:

public class Person implements Comparable<Person> {
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public String name;
  public int age;

  @Override
  public int compareTo(Person other){
    return (age - other.age);
  }
}

Then in your code instead of having an ArrayList<String> use an ArrayList<Person>. Instead of adding "David:43" add new Person("David", 43) to your list.

Then simply sort the list like this:

Collections.sort(yourlist);
Comments