简体   繁体   中英

how to sort integer from listFiles?

I want to sort the integer from listFiles which not included the string. The smallest number will display"The smallest number=" and the biggest number will display"The biggest number="

public static void main(String[] args) {
        // TODO Auto-generated method stub
        File folder = new File("input/");
        File [] files = folder.listFiles();         

        for(int i = 0; i < files.length-1;i++) {

            String fileFullName = files[i].getName();       
            String fileSimple= fileFullName.substring(2,fileFullName.length()-4);           
            long fileNumber =Long.parseLong(fileSimple);

            String fileFullName2 = files[i+1].getName();        
            String fileSimple2= fileFullName2.substring(2,fileFullName2.length()-4);            
            long fileNumber2 =Long.parseLong(fileSimple2);                  
        }                       
    }

The file name included HR20190405.txt, AR20290405.txt,RG20290805.txt,RK21290405.txt

There is suitable method summaryStatistics from IntStream . Using stream api it will look like:

IntSummaryStatistics stat = Arrays.stream(files)
        .mapToInt(file -> Integer.valueOf(file.getName().substring(2, file.getName().length() - 4)))
        .summaryStatistics();

System.out.println(stat.getMin());
System.out.println(stat.getMax());

You were quite close. We will just have to store the maximum & minimum values in variables. Also, the code to fetch the number from file name can be a separate method:

public static void main(String[] args) {

    File folder = new File("input/");
    File [] files = folder.listFiles();      

    //Set first number as smallest and largest   
    long smallest = getNumberFromName(files[0]);
    long largest = smallest;

    //Get number for each file and assign smallest & largest values
    for(int i = 1; i < files.length-1;i++) {
        long nextNumber = getNumberFromName(files[i]);
        if (smallest > nextNumber)
            smallest = nextNumber
        if (largest < nextNumber)
            largest = nextNumber
    }
    System.out.println("The smallest number="+smallest)
    System.out.println("The biggest number="+largest)
}


private static long getNumberFromName(File nextFile) {
    String fileFullName = nextFile.getName();       
    String fileSimple= fileFullName.substring(2,fileFullName.length()-4);           
    return Long.parseLong(fileSimple);
}

Actually based on a previous answer, you can go even further and refine the code to use both the Stream API as well as java.nio . This will save you plenty of time as you won't be needing to perform manual iterations over the array of files you have read.

Also a good trick is to avoid the various magic number during substringing actions. A regex would have been way more suitable to avoid unwanted runtime errors.

Based on the above, a sample code would look like:

private static Optional<IntSummaryStatistics> getMinMax(final String filePath) {
    try (Stream<Path> pathStream = Files.list(Paths.get(filePath))){
        return Optional.of(pathStream
        .map(Path::getFileName)
        .map(Path::toString)
        .map(s -> s.replaceAll("\\D+",""))
        .mapToInt(Integer::valueOf)
        .summaryStatistics());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return Optional.empty();
}

And calling this would as simple as doing this:

public static void main(String[] args) {
    getMinMax("D:\\test").ifPresentOrElse(
        stats -> System.out.println("Min is " + stats.getMin() + " Max is " + stats.getMax()),
        () -> System.out.println("Nothing has been found")
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM