THINK FIRST·CODE LATER

← All labs

Comparator chains

Problem

Write a class Staff (name, department, salary, getters, toString → Lina(IT,9000)) and StaffSort, which reads name department salary lines and prints the list sorted in five ways:

  1. by name, with a hand-written lambda (a, b) -> …;
  2. by salary, with Comparator.comparingInt;
  3. "payroll order": department, then salary descending, then name (comparing(…).thenComparing(…reversed()).thenComparing(…));
  4. the payroll comparator .reversed();
  5. by name length, ties by name;

and finally the highest-paid person (Collections.max; on a tie the alphabetically first name).

For the input

Lina IT 9000
Omar HR 7000
Mei IT 9000
Ana HR 8000
Bo IT 6500

the program prints

by name: Ana(HR,8000) Bo(IT,6500) Lina(IT,9000) Mei(IT,9000) Omar(HR,7000)
by salary: Bo(IT,6500) Omar(HR,7000) Ana(HR,8000) Lina(IT,9000) Mei(IT,9000)
payroll order: Ana(HR,8000) Omar(HR,7000) Lina(IT,9000) Mei(IT,9000) Bo(IT,6500)
reversed: Bo(IT,6500) Mei(IT,9000) Lina(IT,9000) Omar(HR,7000) Ana(HR,8000)
by name length: Bo(IT,6500) Ana(HR,8000) Mei(IT,9000) Lina(IT,9000) Omar(HR,7000)
highest salary: Lina(IT,9000)

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d3-4-data-1.txt

Lina IT 9000
Omar HR 7000
Mei IT 9000
Ana HR 8000
Bo IT 6500
What your program must print for d3-4-data-1.txt
by name: Ana(HR,8000) Bo(IT,6500) Lina(IT,9000) Mei(IT,9000) Omar(HR,7000)
by salary: Bo(IT,6500) Omar(HR,7000) Ana(HR,8000) Lina(IT,9000) Mei(IT,9000)
payroll order: Ana(HR,8000) Omar(HR,7000) Lina(IT,9000) Mei(IT,9000) Bo(IT,6500)
reversed: Bo(IT,6500) Mei(IT,9000) Lina(IT,9000) Omar(HR,7000) Ana(HR,8000)
by name length: Bo(IT,6500) Ana(HR,8000) Mei(IT,9000) Lina(IT,9000) Omar(HR,7000)
highest salary: Lina(IT,9000)

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d3-4-data-1.txt

Windows PowerShell does not understand <:

Get-Content d3-4-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.