简体   繁体   中英

How can I sort a Linked-List based on last names?

I have a program that requests the first and last names of 10 people from the console and then adds them to a Linked List under a single entity, 'fullName'. Is there a way to use Collections.sort() to sort the names based on the last name and not the first. The order of first name then last name needs to be kept. This is what I have so far:

public void requestNames(){

        for(int i = 1; i < 11; i++){

            // Request first name.
            System.out.print("Enter first name of friend # " + i + ":");
            String fName = scanner.nextLine();

            // Request last name.
            System.out.print("Enter last name of friend # " + i + ":");
            String lName = scanner.nextLine();

            // Concatenate first and last name and hold in fullName variable.
            String fullName = fName + " " + lName;

            myList.add(fullName);
        }
        scanner.close();
    }

    public void sortList(){
        Collections.sort(myList);
    }

Yes. Provided that you are using LinkedList from the Java Collections API, you can write a custom comparator for this operation.

Collections.sort(myList, new Comparator<String, String>() {
    public int compare(String left, String right) {
        String leftLast = String.split("\\s")[1];
        String rightLast = String.split("\\s")[1];
        return leftLast.compareTo(rightLast);
    }
}

Graphically, create a LinkedList “Full name” of your first name and last name combined. Perform the following operations on the LinkedList.

  1. Split Full name into two lists, “First name” and “last name” containing your first and last name.
  2. Empty “last name”
  3. Copy “First name” to “last name”.

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