Java - Index (list)

Possible Duplicate:
Alphabetical Sort List

how can I store my entries in alphabetical order, I enter the names in the arraylist:

    persons.add(person);

How to do it?

+3
source share
4 answers

Try the following:

 java.util.Collections.sort(people);
+5
source

implements an interface Comparator< T >

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*/)

+9
source
Collection<Person> listPeople = new ArrayList<Person>();

Person.java 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;
 }

}

, , , , :

Collections.sort(listPeople);
+5

TreeSet ArrayList

0
source

Source: https://habr.com/ru/post/1781832/


All Articles