简体   繁体   中英

How to sort an ArrayList by a users last name

How do I sort an ArrayList by a users last name? My program prints out the names in order by first name. Is there another 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM