Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: How do I sort a TreeSet<Person> by Person's age?

  1. #1
    Junior Member
    Join Date
    Jun 2014
    Posts
    22
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default How do I sort a TreeSet<Person> by Person's age?

     
    public class Person implements Comparable<Person>
    {
        // the age of the person
        private int age;
        //the name of the person
        private String name;
        //the Integer object to wrap the age value;
        private Integer ageWrap;
     
       //Constructor and accessors methods omitted. 
                             .
                             .
                             .
     /**
         * Compare the ages of the persons
         */
        public int compareTo(Person person)
        {
            return getAgeWrap().compareTo(person.getAgeWrap());
        }
    }
     
    import java.util.*;
    public class PersonTreeSet
    {
        // instance variables 
        private TreeSet<Person> setOfPersons;
     
        private String[] persons = {"Vasilis", "Jenny", "Varvara", "Thanasis", "Dimitris", "Dionisia", "Kostas",
                "Eugenia", "Hara", "Antonia"};
        private int maxAge;
     
          //Constructor and main method omitted.
                             .
                             .
                             .
     /**
         * Create people and add them in the TreeSet
         */
        public void createPersons()
        {
            Random rand = new Random();
            for(int index = 0; index < persons.length; index++) {
                Person person = new Person(rand.nextInt(maxAge), persons[index]);
                setOfPersons.add(person);
            }
            System.out.println(setOfPersons.size());
        }
     
        /**
         * Print all the elements of the treeSet
         */
        public void printPersons()
        {
            for(Person person : setOfPersons) {
                System.out.println(person.getName() + " is " + person.getAge() + " years old");
            }
        }
       /**
         * sort persons by age.
         */
        public void sortByAge()
        {
            ArrayList<Person> sortPersons = new ArrayList<Person>();
            sortPersons.addAll(setOfPersons);
            Collections.sort(sortPersons);
            for(Person person : sortPersons) {
                System.out.println(person.getName() + " is " + person.getAge() + " years old");
            }
        }
    }

    The collection library has a class named TreeSet, which is an example of
    a sorted set. Elements in this set are kept in order. Carefully read the description of this class,
    and then write a class Person that can be inserted into a TreeSet, which will then sort the
    Person objects by age.
    This is the exercise I am trying to solve. And this is as far as I have gotten to.
    Is it possible to sort my setOfPersons TreeSet directly? I tried to use
    Collections.sort(setOfPersons)
    method but it wont compile, and I realized that it is not applicable to TreeSet. So I made the
    sortByAge()
    method to do it indirectly...
    I am puzzled though because in the exercise it states
    write a class Person that can be inserted into a TreeSet, which will then sort the Person objects by age.
    meaning that the TreeSet will sort the Person Objects and not my class..
    Any suggestions?


  2. #2
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: How do I sort a TreeSet<Person> by Person's age?

    A TreeSet is always sorted. It will sort itself.
    Please read the API documentation before using a class, it clearly states that:
    All elements inserted into the [Tree]set must implement the Comparable interface. Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the set. If the user attempts to add an element to the set that violates this constraint (for example, the user attempts to add a string element to a set whose elements are integers), the add call will throw a ClassCastException.
    What you need to do is implement the Comparable interface in your Person class.
    The Comparable interface defines a method that will be used for comparison. In this method you can use your age attribute.
    For example:
    public int compare(Person a, Person b) {
            return Integer.compare(a.age, b.age);
    }

  3. #3
    Junior Member
    Join Date
    Jun 2014
    Posts
    22
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: How do I sort a TreeSet<Person> by Person's age?

    I am confused now...I do implement the comparable interface dont I? I implement the compareTo method in Person Class ... The API documentation for the Comparable interface mentions only compareTo(T o) method and this is the one I implemented. So if I got it right I will replace that with the one you suggest and the Persons objects will be sorted by age automatically?

    --- Update ---

    I am SO STUPID.... I didnt notice that I have already solve the exercise.... Just Bu providint the implementation of the compareTo method the the elements of the TreeSet are already sorted by age... Cornix the suggestion you provided me doesnt implement the compareTo method and it doesnt compile since Implement the Comparable<Person> interface in my class signature... Thanks for your time anyway

Similar Threads

  1. First Person Camera
    By Aaron in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 13th, 2010, 01:54 PM
  2. New person Just trying to read a file of ints
    By dubois.ford in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: March 7th, 2010, 11:47 PM