user19693987
user19693987

Reputation: 41

Java - Trying to find largest value in a specific column of a CSV

I was trying to find the largest value in a specific column but so far my code only prints that column on the console. How can I read through the last column only and find the largest value and print that entire row where the largest number is found?

BufferedReader csvReader = null;
try {
    csvReader = new BufferedReader(new FileReader(selectedFile.getAbsolutePath()+"\\FinalResults.csv"));
} catch (FileNotFoundException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}
String line = null;
try {
    while ((line = csvReader.readLine()) != null) {
        String[] cols = line.split(",");
        System.out.println("Coulmn 3= " + cols[2]);
    }
} catch (IOException e) {
    e.printStackTrace();
}   

Updated Code

int largestSoFar = Integer.MIN_VALUE ;
BufferedReader csvReader = null;
            try {
                csvReader = new BufferedReader(new FileReader(selectedFile.getAbsolutePath()+"\\FinalResults.csv"));
                System.out.println(selectedFile.getAbsolutePath()+"\\FinalResults.csv");
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            String line = null;
            try {
                while ((line = csvReader.readLine()) != null) {
                    String[] cols = line.split(",");
                    
                    int number = Integer.parseInt( cols[2] ) ;
                    if ( number > largestSoFar ) { largestSoFar = number ; }
                 
                  //  calculateMinAndMax(cols[2]); 
                    System.out.println(number);
                  //  System.out.println("Coulmn 3= " + cols[2]);
                }
            } catch (IOException e) {

                e.printStackTrace();
            }   
            }
        }

Upvotes: 3

Views: 461

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 339342

Caveat: code shown below is untested.


After your line String line = null;, add a variable to hold the largest number yet found.

…
String line = null;
int largestSoFar = Integer.MIN_VALUE ;

Inside your while loop, parse each input.

int number = Integer.parseInt( cols[2] ) ;

If larger than previously stored, store it in the largestSoFar variable.

if ( number > largestSoFar ) { largestSoFar = number ; }

And test that you have any lines. In the case of no lines, the code above would erroneously report the MIN_VALUE constant as the largest value.


In advanced Java, we might use streams as an alternative approach.

Optional< Integer > result =                            // An `Optional` object may be empty. For example, if the file contains no lines, no largest number exists, so an empty `Optional` would represent that fact. 
    Files                                               // From Java NIO.2, the modern way to handle files.
        .lines( myPath )                                // Make a stream whose elements are each line of text read from file.
        .map( line -> line.split( myDelimiter )[ 2 ] )  // Make a new stream whose elements are the third field of each line.
        .map( thirdField -> Integer :: valueOf )        // Make a new stream whose elements are `Integer` objects parsed from third field text.
        .max() ;                                        // Track the largest `Integer` object, returned wrapped as an `Optional< Integer >`. 

In real work, I would use one of the several excellent libraries available in the Java ecosystem to read and parse a CSV file.

Upvotes: 2

Related Questions