In: Computer Science
Write a comparator that sorts students by Last and First name in ascending order
Please see whole code with the comments:
Code:
// Import all necessary library
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Main
{
public static void main(String[] args)
{
Students[] stu = {
new Students("Smith", "XYZ"),
new Students("Johnson", "DEF"),
new Students("Williams", "Black"),
new Students("Brown", "Yellow"),
new Students("Jack", "Yellow"),
};
// get List view of the students
List<Students> list = Arrays.asList(stu);
// display all students
System.out.println("Complete Students list:");
list.stream().forEach(System.out::println);
// Functions for getting first and last names from an
Students
Function<Students, String> byFirstName =
Students::getFirstName;
Function<Students, String> byLastName =
Students::getLastName;
// Comparator for comparing students by first name then last
name
Comparator<Students> lastThenFirst =
Comparator.comparing(byLastName).thenComparing(byFirstName);
// sort students by last name, then first name
System.out.printf(
"%nstudents in ascending order by last name then first:%n");
list.stream()
.sorted(lastThenFirst)
.forEach(System.out::println);
}
}
class Students
{
private String firstName;
private String lastName;
// constructor
public Students(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
// set firstName
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
// get firstName
public String getFirstName()
{
return firstName;
}
// set lastName
public void setLastName(String lastName)
{
this.lastName = lastName;
}
// get lastName
public String getLastName()
{
return lastName;
}
// return Students's first and last name combined
public String getName()
{
return String.format("%s %s", getFirstName(), getLastName());
}
// return a String containing the Students's information
@Override
public String toString()
{
return String.format("%s %s",getFirstName(), getLastName());
}
}
Output:
Complete Students list:
Smith XYZ
Johnson DEF
Williams Black
Brown Yellow
Jack Yellow
students in ascending order by the last name then
first:
Williams Black
Johnson DEF
Smith XYZ
Brown Yellow
Jack Yellow
The last two are having a surname like yellow then it will consider the first name while sorting.
Brown and Jack so Brown will come first then Jack since the surname is the same.
While copying this code from your end please ensure the indentation of the code:
Otherwise will give the error
Screenshot of the working code output:


Consider the above two screenshot as a one.
You can change the students list as per your requirements must be followed first and last name format.