0

I have data stored in a list of String array (List<String[]> data = reader.readAll();) and I'm trying to store them in a java array (value). Please see the below code. data is getting stored in the array "value" but it's getting replaced all the time and it will show the last value only at the end of the loop. I need to store all the data in an array without replacing. Please help me to resolve this.

String csvfile = "C:\\Users\\…….TestData\\LoginData.csv";

CSVReader reader= new CSVReader(new FileReader(csvfile));

List<String[]> data = reader.readAll();

String[] values = new String[5] ;

try {     
    for (int i=1; i<5; i++)
    {
        values= data.get(i);
        System.out.println(values[1]); //second element is replaced by first
    }
} catch(Exception e) {

}
1

You would not be able to easily convert List<String[]> to String[] since they have different dimensions. It is like when you render 3d scene on a raster you miss the information about objects' depth.

In your case you can convert List<String[]> to String[][] (2d-array) without missing dimension aspect.

String[][] values = data.toArray(new String[][]{});

Running code in debug shows that conversion was performed successfully:

enter image description here

| improve this answer | |
1

the element isn't replaced in your code, you only print always the first element.

This how you can add the elements from a list into an array in java:

List data = new ArrayList();
data.addAll(Arrays.asList("1", "2", "3", "4", "5"));

String[] values = new String[data.size()];
int index = 0;
for (Object s : data) {
      values[index] = s.toString();
      index++;
}

for (String s: values)System.out.println(s);
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.