Search code examples
javastringcsvstring-length

Finding minimum String length of all lines in a CSV and printing them


So let's say I have a CSV file of random alphabets in columns for example's sake:

a
wrrq
jt
pkto
b   

They are in String format and I want to be able to find the minimum String length in this CSV list. In the example given, the minimum being 1 (the maximum being 4). Then I want to print all the minimums in order, resulting in:

a
b

This is my code that reads each line from the top and it's barely anything to a helpful guideline but I'm kind of stuck right now.

    BufferedReader br = new BufferedReader(new FileReader("Example.csv"));
    while ((nextLine = br.readLine()) != null) {

    ...

    }

Is there a way to do this a simple way without using fancy 3rd party scripts. Maybe putting them into an array and then working from there perhaps(?) Keeping in mind that the minimum may not always be 1.


Solution

  • For a single-pass solution…

    Create an empty collection to store results. Read first line, and store it in collection.

    Read another line.

    • If this line is the same length as previously stored line, add to collection.
    • If longer, ignore.
    • If shorter, empty collection and then add.

    Lather, rinse, repeat.