I'm trying to use Lambda expressions in my Java project. My code reads files from a folder, stores them in an array and sorts them in descending order. Other methods will use this code to get the file that contains most recent date.
Arrays.sort(listOfFiles, (File file1, File file2) -> file2.getName().compareToIgnoreCase(file1.getName()));
The output is:
README.txt
forecast-project-export-from-2017-03-06-to-2017-03-10.csv
forecast-project-export-from-2017-02-27-to-2017-03-03.csv
forecast-project-export-from-2017-02-20-to-2017-02-24.csv
forecast-project-export-from-2017-02-13-to-2017-02-17.csv
forecast-project-export-from-2017-02-06-to-2017-02-10.csv
forecast-project-export-from-2017-01-30-to-2017-02-03.csv
forecast-project-export-from-2017-01-23-to-2017-01-27.csv
The output is correct however, the folder contains a README.txt file which I want to Ignore or not have it as element[0] of the array. Is there a way I can use an if statement that only sorts elements if their name contains "forecast-project-export-from". Something like this:
if (o1.getName().contains("forecast-project-export-from") && o2.getName().contains("forecast-project-export-from")) {
return o2.getName().compareToIgnoreCase(o1.getName());
}
tmp.stream().filter( x -> x.startsWith("my-prefix")).sorted( (k1, k2) -> k1.compareTo(k2)).collect(Collectors.toList());README.txtfile, it sounds like what you actually want to do is only include files that match the patternforecast-project-export-from-<date>-to-<date>.csv. CurrentlyREADME.txtin the only problem file, but if you only exclude that file, then if another "bad" file was added to the folder, your code would likely break again. So, thefilterexamples given are a good starting point, but I'd do an inclusive filter for files you want, rather than exclusive for the currently known one you don't.folder.list((dir, filename) -> filename.matches("forecast-project-export-from-\\d{4}-\\d{2}-\\d{2}-to-\\d{4}-\\d{2}-\\d{2}\\.csv"));