Home > Mobile >  Iterate over a List of objects in java
Iterate over a List of objects in java

Time:10-26

I would like to iterate over a csv file and save rows to the database with Spring CrudRepository. From my data I only need the data object, error and meta is not important. When I run a for-loop on my data it looks like this:

for (int i = 0; i < file.size(); i  ) {
            System.out.println(file.get(i));
        }   
[{data=[column1,column2,column3,column4], errors=[], meta={delimiter=,, linebreak=
, aborted=false, truncated=false, cursor=41}}
{data=[data1,data2,data3,data4], errors=[], meta={delimiter=,, linebreak=
, aborted=false, truncated=false, cursor=78}}
{data=[data1,data2,data3,data4], errors=[], meta={delimiter=,, linebreak=
, aborted=false, truncated=false, cursor=134}}]

I tried to write an other loop in the first one, unfortunately it didn't work. How could I read and reference to this section of my list?

[column1,column2,column3,column4],[data1,data2,data3,data4],[data1,data2,data3,data4]

Edit to make it clear: I get a csv file from user on frontend, it should has 4 columns. Something like this one: enter image description here

When I send it to the backend I got this List collection:

On my frontend:

enter image description here

On my backend: enter image description here

CodePudding user response:

You should find out what the objects that you are iterating look like before trying to iterate them. In Java, you can get the type of an object o using o.getClass(), which when printed will tell you the name of the class so you can look up its API. Using a debugger can also let you explore inspect any object (and its class), without having to print anything.

Whatever the class of those objects, they appear to have data, errors, and a meta field - so maybe you can iterate the data by using:

for (int i = 0; i < file.size(); i  ) {
  // file.get(i) probably has a getData() method
  for (Object o : file.get(i).getData()) {
     System.out.println(o);
  }
} 

CodePudding user response:

Use this to parse array or every element of array.

 for (int i = 0; i < file.size(); i  ) {
    for (Object key : file.get(i).keySet()) {
        String keyString = (String) key;
        Object keyvalue = file.get(i).get(keyString);
        if(keyvalue instanceof JSONArray){
        JSONArray array = (JSONArray) keyvalue;
        for (int j = 0; j < array.length(); j  ) {
           System.out.println(array.get(j));
        }
     }
}
  • Related