1
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.

Jacob G.
  • 28,856
  • 5
  • 62
  • 116
Javanewbie
  • 11
  • 2
  • 1
    Possible duplicate of [Sort ArrayList of custom Objects by property](https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) – ernest_k Apr 17 '18 at 21:15
  • @ErnestKiwele That doesn't look like a duplicate to me, as it only sorts by a single field and not multiple. – Jacob G. Apr 17 '18 at 21:32

1 Answers1

2

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.

Jacob G.
  • 28,856
  • 5
  • 62
  • 116