I'm working on a problem where I have to import 3 text files: Doctor, Paitient, Visits. I have to find the top 5 oldest doctors on the list. Currently my method for this is looking like this :
private static void zadanie5(List<Lekarz> lekarz) {
System.out.println("Zadanie5");
lekarz.stream()
.sorted(Comparator.comparing(Lekarz::getDataUrodzenia, Comparator.nullsLast(Comparator.reverseOrder())))
.limit(5)
.forEach(System.out::println);
When run the method will bring up the 5 people although they are not the oldest, the oldest which is displayed by the method is born in 1970, where as on the file there are people born in 1946.
The imported text file with the doctors look's like this: (ID of the doctor, Surname, Name, Speciality, Date of birth, NIP number, Pesel number)
Id_lekarza Nazwisko Imie Specjalnosc Data_urodzenia NIP PESEL
23 Kadaj Monika laryngolog 1965-03-16 879-122-69-94 65031687654
Could you advise what could be the issue here and how I could fix the sorting?
Thanks!
CodePudding user response:
I think that the issue you are having is with the order. When you use the method Comparator.reverseOrder()
you will get the numbers from biggest to smallest. The year in which someone is born will be smaller for older people. An example of this is the year 2020 is more than 1952 even though those born in 1952 are older.
Try to use the code below.
lekarz.stream().sorted(Comparator.comparing(Lekarz::getDataUrodzenia, Comparator.nullsLast(Comparator.naturalOrder())))
.limit(5)
.forEach(System.out::println);