Javanewbie
Javanewbie

Reputation: 11

How to sort two things in Java?

public static void main(String[] args) {

    ArrayList<Employee> unsorted = loadEmployee("NameList.csv", 100);


    Collections.sort(unsorted,(Employee o2, Employee o1)-> o1.getFirstName().compareTo(o2.getFirstName() ));


    unsorted.forEach((Employee)-> System.out.println(Employee));

This prints first name in alphabetical order. But how do you sort first name first then by ID? I have Employee class and have String ID, String firstName. Learning Collections.sorthere.

Upvotes: 1

Views: 62

Answers (1)

Jacob G.
Jacob G.

Reputation: 29680

You're looking for Comparator#thenComparing:

With Collections#sort:

List<Employee> unsorted = loadEmployee("NameList.csv", 100);

Collections.sort(unsorted, Comparator.comparing(Employee::getFirstName)
                                     .thenComparing(Employee::getId));

unsorted.forEach(System.out::println);

With a stream:

loadEmployee("NameList.csv", 100).stream()
                                 .sorted(Comparator.comparing(Employee::getFirstName)
                                                   .thenComparing(Employee::getId))
                                 .forEach(System.out::println);

This sorts first by the Employee's first name and, if two of the names for different Employees are equivalent, it sorts by ID.

Upvotes: 2

Related Questions