-1

I have a program that reads in a text file and will tokenize the words using a comma as a delimiter. It's working fine, but now I need to switch from using a 2-dimensional array where I know how many elements will be in it to using a 2-d ArrayList since I will not know how many elements will be passed into the ArrayList.

here's the working code with the multidimensional array, I'm really just looking for a way to change the below over to use an ArrayList so that i can pass in an unknown amount of elements to the array.

    String filename = "input.txt";
    File file = new File(filename);         
    Scanner sc = new Scanner(file);

    arraySize = sc.nextLine().trim();
    int size = Integer.parseInt(arraySize); 

    // creates a multidimensional array with the size set from the input file.
    String[][] myArray = new String[size][];

    // the outer for loop iterates through each line of the input file to populate the myArray.
    for (int i = 0; i < myArray.length; i++) {
         String line = sc.nextLine();  
         myArray[i] = line.split(","); //splits each comma separated element on the current line.
         //the inner for loop gets each element of myArray and removes any white space.
         for (int j = 0; j < myArray[i].length; j++) {
             myArray[i][j] = myArray[i][j].trim();
         }
    }

this is what I've been working on, the only main difference is that the file will have spaces acting as the delimiter instead of commas. and also that it will read in an unkown number of elements from the file into the array. The add() method was giving me the below error.

The method add(int, List<String>) in the type List<List<String>> is not applicable for the arguments (String)

.

            String filename = "input.txt";
            File file = new File(filename);         
            Scanner sc = new Scanner(file);

//          ArrayList<ArrayList<String>> myArray = new ArrayList<ArrayList<String>>();
            List<List<String>> myArray = new ArrayList<>();

            while(sc.hasNextLine()) {
                 String line = sc.nextLine();  // each line will have an equation
                 String[] equations = line.split("\\s+");

                 for (String s : equations) {
                     s = s.trim();

                    // myArray.add(s); can't figure out how to add into arraylist

                 }                              

            }

            sc.close();  

edit: I'm not trying to pass an existing array to an ArrayList, just trying to find a way get a multidimensional ArrayList to hold an unspecified amount of elements that are read in from an input file, each word from the input file needs to be split using white space as a delimiter, and stored in the ArrayList.

Patrick Parker
  • 4,863
  • 4
  • 19
  • 51
random_user_0891
  • 1,863
  • 3
  • 15
  • 39
  • `myArray.add(Arrays.asList(equations));` – shmosel Mar 22 '18 at 04:37
  • Or you can use a `List`. – shmosel Mar 22 '18 at 04:38
  • @shmosel Using `Arrays.asList(equations)` will end up in missing the `trim()` function filter. – shriyog Mar 22 '18 at 04:40
  • @narush It's not clear why the trim is necessary altogether. Any whitespace would have been removed by the `split()`. – shmosel Mar 22 '18 at 04:41
  • @Scott As @shmosel rightly said, you can avoid `trim()` since the regex `\\s+` eliminates all the whitespaces. – shriyog Mar 22 '18 at 04:48
  • duplicate https://stackoverflow.com/questions/157944/create-arraylist-from-array?rq=1 – mewc Mar 22 '18 at 04:51
  • Possible duplicate of [Create ArrayList from array](https://stackoverflow.com/questions/157944/create-arraylist-from-array) – mewc Mar 22 '18 at 04:52
  • @shmosel can you please explain what you mean by 'Or you can use a List' when I tried `myArray.add(Arrays.asList(equations))` i'm sill getting `The method add(int, List).....is not applicable for the arguments (List)` why is add() looking for an int for one of its parameters? – random_user_0891 Mar 22 '18 at 05:07

4 Answers4

1

Create a new ArrayList object for each line in the file. Populate it and add to your container ArrayList.

String filename = "input.txt";
        File file = new File(filename);         
        Scanner sc = new Scanner(file);

        List<List<String>> myArray = new ArrayList<>();

        while(sc.hasNextLine()) {
             String line = sc.nextLine();  // each line will have an equation
             String[] equations = line.split("\\s+");

             List<String> lineArray = new ArrayList<>();
             for (String s : equations) {
                 s = s.trim();
                 lineArray.add(s);
             }                              
             myArray.add(lineArray);
        }

        sc.close(); 
shriyog
  • 938
  • 1
  • 13
  • 26
0

convert an Array over to an ArrayList

You can do it the following way:

Arrays.stream(equations).map(s -> s.trim()).collect(Collectors.toList());

Edit:

With line.split("\\s+");, you are already splitting the line with one or more consecutive spaces. So you don't have to call trim. So following is a succinct version. Thanks @shmosel.

Arrays.asList(equations);

VHS
  • 9,534
  • 3
  • 19
  • 43
0

Using Files.lines it would look like this:

public static void main(String[] args) throws IOException {
    List<List<String>> words = new ArrayList<>();
    try(Stream<String> lines = Files.lines(Paths.get("input.txt"))) {
        lines.forEach(line -> words.add(Arrays.asList(line.split("\\s+"))));
    }
}

If we also then use Pattern.splitAsStream it would be a little wordier, but I prefer it over Stream.forEach. This approach could in theory be a tiny bit more efficient :

public static void main(String[] args) throws IOException {
    List<List<String>> words;
    Pattern p = Pattern.compile("\\s+");
    try(Stream<String> lines = Files.lines(Paths.get("input.txt"))) {
        words = lines.map(s -> p.splitAsStream(s).collect(toList())).collect(toList());
    }
}
Patrick Parker
  • 4,863
  • 4
  • 19
  • 51
-1
new ArrayList<>(Arrays.asList(array))

duplicate here

mewc
  • 1,253
  • 1
  • 15
  • 24