Strings as custom object fields

Report a typo

Implement the compare() method of PersonComparator class to have natural ordering for name field: the smallest value element should be in the head.
For this task you can use the compareTo() method for string comparison. If this is your code var1.compareTo(var2), the method will return:

  • a negative number when var1 < var2
  • 0 when variables are equal
  • a positive number when var1 > var2

Sample Input 1:

John
James
Bruce

Sample Output 1:

Bruce
James
John
Write a program in Java 17
import java.util.*;

public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Queue<Person> queue = createQueue(scanner);

System.out.println(queue.poll().getName());
System.out.println(queue.poll().getName());
System.out.println(queue.poll().getName());

}

public static Queue<Person> createQueue(Scanner scanner) {
Queue<Person> queue = new PriorityQueue(new PersonComparator());
queue.add(new Person(scanner.nextLine()));
queue.add(new Person(scanner.nextLine()));
queue.add(new Person(scanner.nextLine()));

return queue;
}
}

class Person {
private String name;

public Person(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
___

Create a free account to access the full topic