Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using if statements in Lambda Expressions to sort Arrays

Tags:

java

lambda

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());
}
like image 609
pratikpncl Avatar asked Dec 05 '25 15:12

pratikpncl


1 Answers

Altering a Comparator for this purpose can work, if you're content with storing the read-me as the last value in the array.

(File file1, File file2) -> {
    if(file1.getName().equals("README.txt"))
         return 1;  //readme-file is always "greater" than other files
    if(file2.getName().equals("README.txt"))
         return -1;
    else 
        return file2.getName().compareToIgnoreCase(file1.getName()));
 };

Relevant jls-section

If you want to eliminate the README-file however, you'll have to filter it out (we all love Java8, so here's the stream version):

File[] sorted = Arrays.stream(listOfFiles).filter(f->!f.getName().equals("README.txt")).
    sort(Comparator.comparing(File::getName, String::compareToIgnoreCase)).
    toArray(File[]::new);

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!