Elizabeth Turner
Elizabeth Turner

Reputation: 2871

How to sort by 2 constraints?

So I'm trying to figure this out. I made an arraylist of names with ages that has to be sorted by age then by name (if ages are equal) I'm sure there is an easy way to do this, but our lesson is requiring us to use interfaces. So what I have so far is an array list of people's names and ages then a person class full of methods where I can retrieve information from. How do I sort the list to be passed back into my main class? PersonSorter:

import java.util.ArrayList;
import java.util.Collections;


public class PersonSorter
{
    public static void main(String[] args)
    {
        ArrayList<Person> people = new ArrayList<Person>();

        people.add(new Person("Linda", 63));
        people.add(new Person("Jacob", 5));
        people.add(new Person("Emily", 13));
        people.add(new Person("Jessica", 21));
        people.add(new Person("Emma", 5));
        people.add(new Person("Robert", 80));
        people.add(new Person("Jennifer", 43));

        // PRINT THE LIST OF PEOPLE BEFORE SORTING
        for (Person person : people)
        {
            System.out.println(person);
        }

        System.out.println();//space between the lists

        Collections.sort(people);

        // PRINT THE LIST OF PEOPLE AFTER SORTING
        for (Person person : people)
        {
            System.out.println(person);
        }
    }
}

Person:

public class Person implements Comparable<Person>
{
    /** The person's name */
    private int age;

    /** The person's age */
    private String name;

    /**
     * Constructs a new Person object with the given name and age
     * 
     * @param age of the person
     * @param name of the person
     */
    public Person(String name, int age)
    {
        this.age = age;
        this.name = name;
    }


    /**
     * 
     * Returns the age of the person 
     *
     * @return age
     */
    public int getAge()
    {
        return age;
    }


    /**
     * 
     * Sets the age of the person 
     *
     * @param age
     */
    public void setAge(int age)
    {
        this.age = age;
    }


    /**
     * Returns the name of the person
     * 
     * @return name
     */
    public String getName()
    {
        return name;
    }


    /**
     * 
     * Sets the name of the person
     *
     * @param name
     */
    public void setName(String name)
    {
        this.name = name;
    }



    @Override
    /**
     * Returns a string representation of the person in the form:
     * Person[name = [name], age = [age]]
     */
    public String toString()
    {
        return "Person [name=" + name + ", age=" + age + "]";
    }


    /* (non-Javadoc)
     * @see java.lang.Comparable#compareTo(java.lang.Object)
     */
    @Override
    public int compareTo(Person o)
    {

        return 0;
    }

}

People:

This is the class where I will be pulling the array list and sorting by age then name if need be.

Upvotes: 0

Views: 847

Answers (4)

Janus Troelsen
Janus Troelsen

Reputation: 21300

Google's Guava has a really neat ComparatorChain.

Upvotes: 0

camickr
camickr

Reputation: 324118

If you don't want to keep creating multiple combination Comparators then you can use something like a Group Comparator.

Upvotes: 0

Achintya Jha
Achintya Jha

Reputation: 12843

public int compareTo(Person p) {

        return this.age - p.age;

    }

    public static Comparator<Person> PersonComparator = new Comparator<Person>() {

        public int compare(Person p1, Person p2) {

            String firstPerson = p1.name;
            String secondPerson = p2.name;

            return firstPerson.compareTo(secondPerson);

        }

    };

Add this code to your Person class:

If you want to sort on age try:

    Arrays.sort(people);

If you want to sort on name try:

Arrays.sort(people, Person.PersonComparator); 

Upvotes: 0

Grzegorz Olszewski
Grzegorz Olszewski

Reputation: 1418

You've done most of the job. Just implement compareTo in your Person class:

@Override
public int compareTo(Person o) {
   if (this.age != o.age) {
      return this.age < o.age ? -1 : 1;
   }
   return this.name.compareTo(o.name);
}

Method Collections.sort sorts items according to the order provided by compareTo method.

Upvotes: 5

Related Questions