4

Possible Duplicate:
Sort List Alphabetically

how do i store my inputs in alphabetical order, i am inputting names into an arraylist:

    persons.add(person);

How to do that?

Community
  • 1
  • 1
Jake
  • 123
  • 4
  • 6
  • 12
  • Just use Sort method of Collection where you pass the persons list. –  Dec 23 '10 at 13:13
  • Why don't you guys do your homework TOGETHER: http://stackoverflow.com/questions/1946668/sorting-using-comparator-descending-order-user-defined-classes. It's called a social activity :) – Lukas Eder Dec 23 '10 at 13:20

4 Answers4

9

implements Comparator< T > interface

class A implements Comparator < Person > {

    @Override
    public int compare(Person o1, Person o2) {
        if(o1.getName() != null && o2.getName() != null){
            return o1.getName().compareTo(o2.getName());
        }

        return 0;
    }

}

then use Collections.sort(/* list here */, /* comparator here*/)

5

Try this:

 java.util.Collections.sort(people);
Gerhard Presser
  • 464
  • 1
  • 4
  • 14
5
Collection<Person> listPeople = new ArrayList<Person>();

The class Person.java will implements Comparable

public class Person implements Comparable<Person>{

public int compareTo(Person person) {
  if(this.name != null && person.name != null){
   return this.name.compareToIgnoreCase(person.name);
  }
  return 0;
 }

}

Once you have this, in the class you're adding people, when you're done adding, type:

Collections.sort(listPeople);
Gondim
  • 3,038
  • 8
  • 44
  • 62
0

use TreeSet instead of ArrayList

Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
  • 2
    No, the thing is that i have to use ArrayList because i have to learn it. – Jake Dec 23 '10 at 13:09
  • 3
    That's not really a very good answer. TreeSet is a set, not a list. If he follows blindly this answer, he could go into problems (notably, no more duplicate elements) without knowing why. – Valentin Rocher Dec 23 '10 at 13:19
  • The question was how to store the elements in alphabetical order, no restrictions on the collection in the question. The fact that he is using array list doesn't mean anything. – Vladimir Ivanov Dec 23 '10 at 13:22