Comparator.comparing

Lab Java Intermediate 20 points

Read people name city age. Sort by city, then by age descending, then by name, using Comparator.comparing(...).thenComparing(...). Print name city age.

Input

n, then n lines.

Output

n lines.

Example

Input

5
ann pune 30
bob delhi 25
cy pune 41
dan delhi 25
eve goa 19

Output

bob delhi 25
dan delhi 25
eve goa 19
cy pune 41
ann pune 30
Sample input available Sample output available
Editor
Java

Hints

Person::getCity is a method reference - shorthand for p -> p.getCity().

reversed() flips one comparator.

Solution explanation

Comparator chains read like a sentence and avoid hand-written compare logic.

Show solution
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

class Person {
    final String name, city;
    final int age;

    Person(String name, String city, int age) {
        this.name = name;
        this.city = city;
        this.age = age;
    }

    String getName() { return name; }
    String getCity() { return city; }
    int getAge() { return age; }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        List<Person> people = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            people.add(new Person(sc.next(), sc.next(), sc.nextInt()));
        }
        people.sort(Comparator.comparing(Person::getCity)
                .thenComparing(Comparator.comparingInt(Person::getAge).reversed())
                .thenComparing(Person::getName));
        for (Person p : people) {
            System.out.println(p.name + " " + p.city + " " + p.age);
        }
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD