Search code examples
javaarraylistfilewriter

Writing ArrayList of objects to textfile using filter


(Disclaimer: I am not done writing the coding, so I have been using lousy names to identify things.)

I have an ArrayList of PersonObjects called PersonIndex. The parameters of the PersonObjects are as follows: Name, Age, Gender, Height.

What I am trying to do is process the list and depending on what the last name starts with, it gets written to a different text file.

Because it is in bad taste to try combining three write methods to one writer, I have three different ones which are then called into a single method.

That method is as follows:

public void fullWriteNames(){
    writeNamesA2K();
    writeNamesL2R();
    writeNamesS2Z();
}

I know the general layout of the writer method which is as follows:

String stopper = "stop";
    try{
        personWriter = new FileWriter(fileName2, true);
        personWriter.write(*stuff to write*);
        personWriter.close();
    }
    catch(IOException ioException){
        System.out.println("Error.");
    }

The issue I am having is how to use an if statement by the .write line to filter the objects. I know I need to use .startsWith, but otherwise I am clueless.

Any help would be appreciated. If there is any coding I left out here which would be relevant, please let me know.


Solution

  • Since characters are really just numbers, you could do something like this:

    public void fullWriteNames() {
        char first = lastname.charAt(0);
    
        if (first >= 'A' && first <= 'K') 
            writeNamesA2K();
        else if (first >= 'L' && first <= 'R')
            writeNamesL2R();
        else if (first >= 'S' && first <= 'Z')
            writeNamesS2Z();
    }
    

    I'm assuming here that the lastname variable is your PersonObject's last name.