Question

I am having a resultList which is a string list were each element in this list is also a List<String>. Now I want to put my data into a csv sheet. For that I am using opencsv.

    List<String[]> data = new ArrayList<String[]>();
    for(int m = 0; m < resultList.get(0).size(); m++) {
        for (int i = 0; i < resultList.size(); i++) {

            data.add(new String[] {resultList.get(i).get(m).toString()});

        }
    }

    writer.writeAll(data);

    //close Writer
    writer.close();

My data should look like that:

enter image description here

However, my implementation gives me that:

enter image description here

In my implementation I am taking, knowing that every sublist has the same length, from each sublist the first element and add it to the array. Why am I getting this long row?

I appreciate your replies!

Was it helpful?

Solution

Because your loop is incorrect. You constructed a new String array in every inner loop, so every array has only on element. Try the following code:

List<String[]> data = new ArrayList<String[]>();
for(List<String> strlist : resultList) {

    String[] array = new String[strlist.size()];
    int offset = 0;
    for(String s : strlist) {
        array[offset ++] = s;
    }
    data.add(array);
}

============== Edited bellow ==================

I've re-ordered the loop to match your output requirement. Also, a sample input is provided to test the algorithm.

List<List<String>> resultList = new ArrayList<List<String>>();
for (int i = 1; i <= 9; i++) {

    List<String> innerList = new ArrayList<String>();
    resultList.add(innerList);
    for (int j = 1; j <= 9; j++) {
        innerList.add(j + "");
    }
}

List<String[]> data = new ArrayList<String[]>();

for(int m = 0; m < resultList.get(0).size(); m++) {

    String[] array = new String[resultList.size()];
    for (int i = 0; i < resultList.size(); i++) {
        array[i] = resultList.get(i).get(m).toString();
    }
    data.add(array);
}
for(String[] array : data) {
    System.out.println(Arrays.toString(array));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top