Implementing a comparator several times in a file of one class

I have code to sort paths by date modified. I also want to write code to sort the paths in reverse order, and later I might want to add some other sorting methods. Is there a way to do all sortings from one class file? Or I need to create another class PathSortByDateReverse, PathSortByCreated, PathSortByFoo, etc. Also, how would I use different sorting methods?

import java.nio.file.Path;
import java.util.Comparator;

public class PathSortByDate implements Comparator<Path> {

@Override
public int compare(Path first, Path second) {
    long seconddate = second.toFile().lastModified(); // get just the filename
    long firstdate = first.toFile().lastModified();

    if (firstdate == seconddate) {
        return 0;
    } else if (firstdate > seconddate) {
        return 1;
    } else {
        return -1;
    }
}
}

Then I call it from another class:

public static ArrayList<Path> sortArrayListByDate(ArrayList<Path> pathlist) {
    Collections.sort(pathlist,new PathSortByDate());
    return pathlist;
}    
+5
source share
3 answers

Why not go for anonymous inner classes?

public static final Comparator<Person> ID_DESC
     = new Comparator<Person>() {
      public int compare(Person p1, Person p2) {
         return -1 * p1.getId().comparedTo(p2.getId());
         // reversed order
      }
    };
+3
source

. , "private" " factory", . PathComparator. , .

import java.nio.file.Path;
import java.util.Comparator;

final public class PathComparator implements Comparator<Path> {

// comparator for in order
final private static PathComparator ascendingOrderComparatorDate = new PathComparator(true);
// comparator for reverse order
final private static PathComparator descendingOrderComparatorDate = new PathComparator(false);

final private int isAscendingOrderInt;

final public PathComparator getPathComparator(boolean isAscendingOrder) {
    return isAscendingOrder ? ascendingOrderComparatorDate : descendingOrderComparatorDate;
}

private PathComparator(boolean isAscendingOrder) {
    this.isAscendingOrderInt = isAscendingOrder ? 1 : -1;
}

@Override
public int compare(Path first, Path second) {
    // for optimization (not required but highly recommended)
    if(first == second) return 0;

    long seconddate = second.toFile().lastModified(); // get just the filename
    long firstdate = first.toFile().lastModified();

    if (firstdate == seconddate) {
        return 0;
    } else if (firstdate > seconddate) {
        return isAscendingOrderInt * 1;
    } else {
        return isAscendingOrderInt * -1;
    }
}}
+2

you don't need to do a reverse comparator, just do it and cancel it with

Collections.reverseOrder()
+1
source

All Articles