RAJ METRE
RAJ METRE

Reputation: 31

how to sort an arrayList containing files based on extentions

File [] templatesList = templateFileList.toArray(new File[0] );
Arrays.sort(templatesList,ExtensionFileComparator.EXTENSION_INSENSITIVE_REVERSE);

templatesList contains files like

First reverse sort based on last extension, then sort based on basename, then sort numbers. After sorting, expected output is

My Code:

    File [] templatesList = templateFileList.toArray(new File[0] );
    List <File> tempList = Arrays.asList(templatesList);
    tempList.stream().sorted(ExtensionFileComparator.EXTENSION_INSENSITIVE_REVERSE.
            thenComparing(NameFileComparator.NAME_INSENSITIVE_COMPARATOR));     

        List <File> templateFileList1 = new ArrayList(Arrays.asList(templatesList));
        Collections.sort(templateFileList1, new Comparator <File>() {

            @Override
            public int compare(File f1, File f2) {
                return Integer.parseInt(FilenameUtils.getExtension(FilenameUtils.getBaseName(f1.toString())))-
                        Integer.parseInt(FilenameUtils.getExtension(FilenameUtils.getBaseName(f2.toString())));
            }
        });

Upvotes: 0

Views: 245

Answers (2)

RAJ METRE
RAJ METRE

Reputation: 31

if someone looking for answer

File [] templatesList = templateFileList.toArray(new File[0] );
    Arrays.sort(templatesList, ExtensionFileComparator.EXTENSION_INSENSITIVE_REVERSE
            .thenComparing(NameFileComparator.NAME_INSENSITIVE_COMPARATOR).thenComparing(new Comparator <File>() {
                @Override
                public int compare(File f1, File f2) {
                    String file1 = FilenameUtils.getBaseName(f1.toString());
                    String file2 = FilenameUtils.getBaseName(f2.toString());

                    String ext1 = FilenameUtils.getExtension(file1);
                    String ext2 = FilenameUtils.getExtension(file2);

                    if ((StringUtils.isNumericSpace(ext1)) &&(StringUtils.isNumericSpace(ext2))) {
                        int t1= Integer.parseInt(ext1);
                        int t2= Integer.parseInt(ext2);
                        return t1-t2;
                    }
                    else {
                    return 0;
                    }
                }                   
            }));

Upvotes: 0

davidxxx
davidxxx

Reputation: 131336

You could mix ExtensionFileComparator and NameFileComparator from Apache commons Comparators.
With Java 8 :

Arrays.sort(templatesList, ExtensionFileComparator.EXTENSION_INSENSITIVE_REVERSE
              .thenComparing(NameFileComparator.NAME_INSENSITIVE_COMPARATOR));

Or write it without any API with a little more boiler plate code.

Upvotes: 1

Related Questions