简体   繁体   中英

Can't iterate over objects in a Java for…loop

I can't add to my list this query:

// This query always return List<Object[]>
Query buscarRad = AreaPrincipal.em.createNamedQuery("Rad.buscarPorCuil");
buscarRad.setParameter("cuil", cuil);

List<Object[]> listaRad = buscarRad.getResultList();

int i = 0;
for (Object[] filaRad : listaRad) {
//  if (filaRad[i].equals(null)) {
    if (filaRad[i] != null) {
        lvRad.getItems().add(filaRad[i].toString());
    }
    i++;
    }

This is my vector listaRad:

I need all values not null

...but my objects list break at first value and finalize. What's wrong?

You need to use nested loops to iterate over all rows, and then to iterate over all columns within each row. Try this:

for (Object[] filaRad : listaRad) { //for DB rows
    for (int i = 0; i < filaRad.length; i++) { //for DB columns within a row
        if (filaRad[i] != null) {
            lvRad.getItems().add(filaRad[i].toString());
        }
    }
}

Ideally you should put each column's value in an object's field rather than looping and converting them to toString() . Something like this:

List<MyDbRow> rows = new ArrayList<>();
for (Object[] filaRad : listaRad) {
    MyDbRow row = new MyDbRow();
    row.setId(fileRad[0]); //may require casting
    row.setName(fileRad[1]);

    rows.add(row);
}

See if this works for you. First you can put all elements at one level in an Object array list. After that you can loop through that list and check for null elements.

// This query always return List<Object[]>
Query buscarRad = AreaPrincipal.em.createNamedQuery("Rad.buscarPorCuil");
buscarRad.setParameter("cuil", cuil);

List<Object[]> listaRad = buscarRad.getResultList();
List<Object> finalList = new ArrayList<>();

int i = 0;
for (Object[] filaRad : listaRad) {
  finalList.add(Arrays.asList(filaRad));
}

for(Object o : finalList){
  if (o != null) {
        lvRad.getItems().add(o.toString());
  }
}

In java 8 you can do like this assuming that lvRad.getItems() is a list 
itself

lvRad.getItems().addAll(finalList.stream()
  .filter(Objects::nonNull)
  .collect(Collectors.toList()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM