DensityAwareFileComparator implements Comparator<File> { @Override public int compare(@NotNull File file1, @NotNull File file2) { int c = -Boolean.compare(myDirectories.contains(file1), myDirectories.contains(file2)); if (c != 0) { return c; } String path1 = file1.getAbsolutePath(); String path2 = file2.getAbsolutePath(); Density density1 = pathToDensity(path1 + File.separator); Density density2 = pathToDensity(path2 + File.separator); c = Boolean.compare(density1 != null, density2 != null); if (c != 0) { return c; } if (density1 != null && density2 != null && density1 != density2) { return Integer.compare(density2.getDpiValue(), density1.getDpiValue()); } return path1.compareTo(path2); } DensityAwareFileComparator(@NotNull Set<File> directories); @Override int compare(@NotNull File file1, @NotNull File file2);  }
@Test public void testContract() { Comparator<File> comparator = new DensityAwareFileComparator(Collections.emptySet()); List<File> files = Arrays.asList( new File("/res/mipmap-mdpi"), new File("/res/drawable-hdpi"), new File("/res/mipmap") ); files.sort(comparator); assertThat(comparator.compare(files.get(0), files.get(1))).isLessThan(0); assertThat(comparator.compare(files.get(1), files.get(2))).isLessThan(0); assertThat(comparator.compare(files.get(0), files.get(2))).isLessThan(0); }