java - alphabetical order (list) [duplicate]

我只是一个虾纸丫 提交于 2019-12-22 08:44:19

问题


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?


回答1:


Try this:

 java.util.Collections.sort(people);



回答2:


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




回答3:


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



回答4:


use TreeSet instead of ArrayList



来源:https://stackoverflow.com/questions/4518997/java-alphabetical-order-list

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