Anu
Anu

Reputation: 17

How to store data in a string array using java collection

I have stored data in a List<String[]> and need to store those data into an another String array using a loop. I have created a String array (value) and stored data in there but the issue is first element is getting replaced by second inside the loop and it will show only the last element at the end of the loop.

CSVReader reader = new CSVReader(new FileReader(csvfile));
List<String[]> data = reader.readAll();
String[] values = new String[5];
for (int i = 1; i < 5; i++) {
    values = data.get(i);
    System.out.println(values[1]); // data is getting replaced here
}
System.out.println(values[1]); // this will show only the last stored value

Upvotes: 0

Views: 3766

Answers (5)

Andrew Wang
Andrew Wang

Reputation: 1

Your data variable contains a list of String[] (string arrays). Your for loop is attempting to store them in values which is a single String[].

Depending on what you are trying to do, you can do as the comments suggest and make a 2D String array. However, the fact that you want to remove them from a perfectly good list of String[]'s leads me to believe you probably want them in one big String[].

Below is an example of how to put the first N (in this case 5) words you parse from the csv into the values variable. However, we would be able to give you better guidance if you provided what the ultimate use case of your code snippet is.

    // initialize test data
    List<String[]> data = new ArrayList<String[]>();
    String[] a = {"a1", "a2"};
    String[] b = {"b1", "b2"};
    String[] c = {"c1", "c2"};
    data.add(a);
    data.add(b);
    data.add(c);

    // big N is how many words you want
    int N = 5;
    // little n tracks how many words have been collected
    int n = 0;
    String[] values = new String[N];
    // loop through csv collect
    for (int i = 0; i < data.size(); i++){
        String[] cur = data.get(i);
        // loop through the strings in each list entry
        for (int j = 0; j < cur.length; j++){
            // store value and increment counter
            values[n] = cur[j];
            n++;
            // stop if maximum words have been reached
            if (n >= N)
                break;
        }
        // stop if maximum words have been reached
        if (n >= N)
                break;
    }

    for (int i = 0; i < values.length; i++)
        System.out.println(values[i]);

Upvotes: 0

Michel_T.
Michel_T.

Reputation: 2821

    // generating data
    List<String[]> data =
            Stream.iterate(0,  n -> n + 1)
                    .limit(10)
                    .map(i -> new String[]{"a" + i, "b" + i, "c" + i, "d" + i, "e" + i, "f" + i})
                    .collect(Collectors.toList());

    String[][] values = new String[data.size()][];

    // copy the data
    for (int i = 0; i < data.size(); i++)
    {
        values[i] = data.get(i).clone();
    }

    //print the result
    Arrays.stream(values).map(Arrays::toString).forEach(System.out::println);

Upvotes: 1

Ousmane D.
Ousmane D.

Reputation: 56453

  1. Lists are 0 indexed so unless you intentionally want to skip the first element then don't start the loop iteration at 1 rather at 0.
  2. Yes, when performing the last println after the loop only data related to the last String[] is shown because at each iteration you're updating values i.e. values = data.get(i); to store the current String[] hence the aforementioned outcome.
  3. You probably want a String[][] as opposed to String[] because each String[] represents a line of the file.

Thus, assuming you only want to get the first five lines from data you can do it as:

String[][] lines = data.subList(0, 5).toArray(String[][]::new);

or for all the lines read:

String[][] lines = reader.readAll().toArray(String[][]::new);

and you can test it with:

System.out.println(Arrays.deepToString(lines));

Upvotes: 1

bautigaraventa
bautigaraventa

Reputation: 121

I think you have a little error inside the for loop. Try this:

CSVReader reader = new CSVReader(new FileReader(csvfile));
List<String[]> data = reader.readAll();
String[] values = new String[5];
for (int i = 1; i < 5; i++) {
    values[i] = data.get(i);
    System.out.println(values[1]); // data is getting replaced here
}
System.out.println(values[1]); // this will show only the last stored value

I think you are missing the "[i]" at the first line inside the for loop.

Upvotes: 0

Tamir Abutbul
Tamir Abutbul

Reputation: 7661

Replace :

for (int i = 1; i < 5; i++) {
values = data.get(i);
System.out.println(values[1]); // data is getting replaced here}

With:

for (int i = 0; i < 5; i++) {
values = data.get(i);
System.out.println(values[1]); // data is getting replaced here}

Upvotes: 0

Related Questions