java - alphabetical order (list) [duplicate]

吃可爱长大的小学妹 提交于 2019-12-05 15:25:38
Gerhard Presser

Try this:

 java.util.Collections.sort(people);

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

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);

use TreeSet instead of ArrayList

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!