1

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?

1
  • 2
    Use Collections.sort() with a Comparator that does the age parsing. Commented Sep 7, 2016 at 17:58

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the quick reply! Seems like exactly what I'm looking for! I'll try it out, appreciate it!
@David Happy to help
Hey @nhouser9, it worked very fell, there is just one problem. It prints out from lowest to highest. Is there any way to change this? Edit: I managed to figure it out, here is the simple solution for anyone that runs into this problem as well: Collections.sort(people, Collections.reverseOrder());
@David Yes you can simply change your compareTo method with any custom logic you want. To go highest to lowest, change the order of subtraction. You could even sort by name using return name.compareTo(other.name). Everything pertaining to the ordering of your elements can be controlled by how you are comparing those elements.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.