Search code examples
javaarrays

Appending to array in Java


I have a problem with this code

String[] strLines = null;

while ((strLine = br.readLine()) != null){
    strLines = strLine.split("\\s");
    System.out.printf("next line - %s\n", strLine);
    for(String asd : strLines) {
        System.out.printf("array element - %s\n", asd);
    }
    System.out.println(strLines.length);
}

I'm trying to make a program read from file and then write all unique words into another file. The problem I'm having is that strLines array (which I later convert to Set) is overwritten with every iteration of while loop. Is it possible to somehow append to this array or should I use another way to store my words?

This might be a very beginner question (I've only been coding for a couple of months irregularly), but I couldn't find an answer to it anywhere. Thanks in advance!


Solution

  • There's no reason to create an array if all you do with it is converting it to a set later. Simply add to your set in the while loop:

    String foo = "foo bar baz foo bar baz";
    Set<String> fooSet = new HashSet<>();
    fooSet.addAll(Arrays.asList(foo.split("\\s")));
    

    For your example

    Set<String> fooSet = new HashSet<>();
      
    while ((strLine = br.readLine()) != null){
        fooSet.addAll(Arrays.asList(strLine.split("\\s")));
    }
       
    

    Or, in Java 9+, you can directly create an unmodifiable Set from the array by calling Set.of.

    Set < String > set = Set.of( myArray ) ;