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.sort
here.
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 Employee
s are equivalent, it sorts by ID.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.