I'm having a problem continuing. I have a list and in each position contains a String (within the phrase there is at the end a date)
Example:
I am new here 20/8/2019
I want to sort the list this way: In position zero I want the phrase containing the oldest date and the following positions the date will be more recent.
I tried to use SimpleDateFormat and Date, but I didn't know how to do it.
String variable, variable2, c;
int d = 0;
for(int i = 0; i < lista.size(); i++) {
for(int j = 1; j <lista.size(); j++) {
variable = lista.get(i);
variable2 = lista.get(j);
c = compareDates(variable, variable2);
lista.add(d,c);
d++;
}
}
private static Date compareDates(String variable, String variable2) throws ParseException {
SimpleDateFormat formateador = new SimpleDateFormat("dd/MM/yyyy");
String var = formateador.format(variable);
String var2 = formateador.format(variable2);
if (var.before(var2)) {
return var;
} else {
if (var2.before(var1)) {
} else {
}
return null;
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from Date to String
at Ejercicio.ClaseMain.leerDes(ClaseMain.java:124)
Line 124: c = compareDates(variable, variable2);
Visual example: Each position in the list has a phrase with a date:
The thing is, I read a .txt file, where there are several lines. Contents of the file:
Sevilla reserves himself to Apoel and wins without brilliance; sport Julen Lopetegui revolutionized the eleven with the aim of giving rest to the regulars, which did not prevent his team from adding his second triumph of the competition sportyou 10/10/2019
A painting by Banksy of the British Parliament occupied by chimpanzees, sold >for 11 million euros culture An oil of artist Banksy representing the British House of Commons full of chimpanzees was topped on Thursday at an auction in London for 9.8 million pounds (11 million euros) 10/2019
I use a while to read the file line and save each line at each position in the list, and I want to sort the list. Old date ---> recent date.
My solution would be:
List<String> lista = List.of(
"Sevilla reserves himself to Apoel … sportyou 10/10/2019",
"I am new here 20/8/2019",
"A painting by Banksy … 19/10/2019");
List<String> sortedList = lista.stream()
.map(s -> new Object() {
String theString = s;
LocalDate date = extractDate(s);
})
.sorted(Comparator.comparing(obj -> obj.date))
.map(obj -> obj.theString)
.collect(Collectors.toList());
sortedList.forEach(System.out::println);
Output from this is:
I am new here 20/8/2019 Sevilla reserves himself to Apoel … sportyou 10/10/2019 A painting by Banksy … 19/10/2019
The extractDate
method that I am using is:
private static Pattern datePattern = Pattern.compile("\\d{1,2}/\\d{1,2}/\\d{4}$");
private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");
private static LocalDate extractDate(String fullString) {
Matcher m = datePattern.matcher(fullString);
if (m.find()) {
String dateString = m.group();
return LocalDate.parse(dateString, dateFormatter);
} else {
throw new IllegalArgumentException("String doesn’t end with a date: " + fullString);
}
}
For efficient sorting of the strings — it only matters if there are many — I am extracting the trailing date and parsing it only once for each string (not for every comparison). I am parsing into LocalDate
and use these for sorting. In order to get the original strings out after sorting I have put both the String
and the LocalDate
into an object and then sort these objects. It may surprise some that I can use an anonymous subclass of Object
in this way, but it works nicely.
I recommend you don’t use SimpleDateFormat
and Date
. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead I am using LocalDate
and DateTimeFormatter
, both from java.time, the modern Java date and time API.
Java has nice sorting facilities built-in. If writing your own sorting algorithm was for an exercise, that’s a good exercise. Frankly you still had a way to go before your sorting would work. You may want to read up on sorting algorithms, there’s a lot written, also on the WWW. For production code you should rely on a library method.
Link: Oracle tutorial: Date Time explaining how to use java.time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With