简体   繁体   English

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

[英]How to sort an ArrayList by a users last name

How do I sort an ArrayList by a users last name? 如何按用户姓氏对ArrayList进行排序? My program prints out the names in order by first name. 我的程序按名字打印出名称。 Is there another collections.sort(..); 还有另一个collections.sort(..); method? 方法? Or a way without making a map. 或者没有制作地图的方式。

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

Use Person class which would implement Comparable<Person> interface like: 使用将实现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;
    }
}

Then you can create list of Person object and use Collections.sort method to sort your list. 然后,您可以创建Person对象列表,并使用Collections.sort方法对列表进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过userNumber对用户的ArrayList进行排序 - How to sort an ArrayList of users by userNumber 如何在Java中按名称对ArrayList值进行排序 - How to sort ArrayList values by name in java 尝试按姓氏排序对象的ArrayList,如果姓氏相同,则按名字排序 - Trying to sort an ArrayList of Objects by last name, then by first name if last names are the same 如何按字母顺序按名字和姓氏排序 - How to sort by first name alphabetically and by last name 按名称对ArrayList项目进行排序 - Sort ArrayList items by name 我试图对从csv文件读取的arraylist进行排序以按姓氏,邮政编码和状态排序 - Im trying to sort an arraylist that was read from a csv file to sort by last name, zip code, and state 如何按时间戳对对象的ArrayList进行排序并获取最后五个元素 - How to sort ArrayList of objects by timestamp and get last five elements 如何根据最后一列的最大值对多个字符串的数组列表进行排序? - How to sort an arraylist of multiple strings based on the highest value of the last column? 如何在 ArrayList 中搜索员工姓名(仅搜索姓氏) - How to search the ArrayList for a Employee name (searched only for last name ) 如何根据名称对一个数组列表进行排序,并且该数组列表包含带有姓名缩写的名称? - How can I sort an arraylist based on the name and the Arraylist contains name with Initial of a person?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM