如何按用户姓氏对ArrayList进行排序

时间:2015-02-17 14:44:58

标签: java sorting arraylist collections

如何按用户姓氏对ArrayList进行排序?我的程序按名字打印出名称。还有另一个collections.sort(..);方法吗?或者没有制作地图的方式。

public static void main(String[] args) throws FileNotFoundException {
    String check = "y";
    do {
        Scanner fileRead = new Scanner(System.in);
        System.out.println("Enter the name of the file: ");
        File myFile = new File(fileRead.next());
        ArrayList<String> names = new ArrayList<>();

        Scanner scanTwo = new Scanner(myFile);

        while (scanTwo.hasNextLine()) {
            names.add(scanTwo.nextLine());
        }
        Collections.sort(names);
        for (String name : names) {
            System.out.println(name);
        }

        System.out.println();
        Scanner ans = new Scanner(System.in);
        System.out.println("Add another? y/n ");
        check = ans.next();
    } while (check.equals("y"));
} 

1 个答案:

答案 0 :(得分:0)

使用将实现Comparable<Person>界面的Person类,如:

public class Person implements Comparable<Person> {
    String fname;
    String lname;
    //getter setter
    public int compareTo(Person person) {
        int comparedFname = this.fname.compareTo(person.getFname());
        if (comparedFname == 0) {//if fname are same then compare by last name
            return this.lname.compareTo(person.getLname());
        }
        return comparedFname;
    }
}

然后,您可以创建Person对象列表,并使用Collections.sort方法对列表进行排序。