I'm trying to sort a string which has this format:
Test: XX Genere: Maschio Eta: YY Protocollo: A Date:28/08/2019
This is the method I used to sort by the parameter Eta which is an Int:
Collections.sort(user_list, new Comparator<String>() {
public int compare(String o1, String o2) {
return Comparator.comparing(this::extractInt)
.thenComparing(Comparator.naturalOrder())
.compare(o1, o2);
}
private int extractInt(String s) {
try {
return Integer.parseInt(s.split(":")[1].trim());
} catch (NumberFormatException exception) {
return -1;
}
}
});
How can I convert it to sort Date objects assuming that the Date parameter will never be null? I tried to make an extractDate method but then I don't know what to insert where there is Comparator.naturalOrder()
.
You might want to do it this way:
// Creating some dummy data
List<String> userList = Arrays.asList("Test: XX Genere: Maschio Eta: YY Protocollo: A Date:28/08/2019",
"Test: XX Genere: Maschio Eta: YY Protocollo: A Date:26/08/2019",
"Test: XX Genere: Maschio Eta: YY Protocollo: A Date:30/08/2019",
"Test: XX Genere: Maschio Eta: YY Protocollo: A Date:12/08/2019");
// Sorting based on LocalDate
userList.sort(Comparator.comparing(s -> {
String stringDate = s.substring(s.lastIndexOf(':') + 1).trim();
return LocalDate.parse(stringDate, DateTimeFormatter.ofPattern("dd/MM/yyyy"));
}));
// printing the lists
userList.forEach(System.out::println);
Sorted Result:
Test: XX Genere: Maschio Eta: YY Protocollo: A Date:12/08/2019
Test: XX Genere: Maschio Eta: YY Protocollo: A Date:26/08/2019
Test: XX Genere: Maschio Eta: YY Protocollo: A Date:28/08/2019
Test: XX Genere: Maschio Eta: YY Protocollo: A Date:30/08/2019
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.