Java sort String array of file names by their extension

前端 未结 8 775
后悔当初
后悔当初 2021-01-13 02:29

I have an array of filenames and need to sort that array by the extensions of the filename. Is there an easy way to do this?

8条回答
  •  终归单人心
    2021-01-13 02:48

        String DELIMETER = File.separator + ".";
        List orginalList = new CopyOnWriteArrayList<>(Arrays.asList(listOfFileNames));
        Set setOfuniqueExtension = new TreeSet<>();
    
        for (String item : listOfFileNames) {
            if (item.contains(".")) {
                String[] split = item.split(DELIMETER);
                String temp = "." + split[split.length - 1];
                setOfuniqueExtension.add(temp);
            }
        }
    
        List finalListOfAllFiles = new LinkedList<>();
        setOfuniqueExtension.stream().forEach((s1) -> {
            for (int i = 0; i < orginalList.size(); i++) {
                if (orginalList.get(i).contains(s1)) {
                    finalListOfAllFiles.add(orginalList.get(i));
                    orginalList.remove(orginalList.get(i));
                    i--;
                }
            }
        });
    
        orginalList.stream().filter((s1) -> (!finalListOfAllFiles.contains(s1))).forEach((s1) -> {
            finalListOfAllFiles.add(s1);
        });
    
        return finalListOfAllFiles;
    

提交回复
热议问题