Solution of adding judgment error in the iterative process of Java iterator iterator

        The first time I tried to use a blog to record my Xiaobai’s learning process, which is mainly convenient for me to query in the future, but it would be great if I could help other friends!

1、 Scenario description

        This is the function of reading data from the database and then exporting excel tables. The value is assigned by the iterator to realize the export. The code is as follows:

protected void generate() {
   XSSFCellStyle xssfCellStyle = defaultStyle();
   defineHeader(this.meta);
   headerDataCount = this.defaultSheet.getPhysicalNumberOfRows();
   for (int i = 0; i < this.data.size(); i++) {
      List<Map<String, Object>> cellList = this.data.get(i);
      for (int j = 0; j < cellList.size(); j++) {
         renderCell(0, i, String.valueOf(i + 1), xssfCellStyle);
         Iterator<Object> iterator = cellList.get(j).values().iterator();
         while (iterator.hasNext()) {
            String value = String.valueOf(iterator.next());
            renderCell(j + 1, i, value, xssfCellStyle);
            beautifyColumn(j + 1, value, xssfCellStyle);
         }
      }
   }
}

        The problem encountered is that the null value (null value) displayed in the Oracle library is displayed as “null” in the exported excel table. I want to add a judgment during iteration to make the read null directly change to “”.

2、 Something went wrong

I changed it this way:

   String value = iterator().next()==null?"":String.valueOf(iterator().next());

However, an error is reported:

         java.util.NoSuchElementException

3、 Settle

Cause of problem:

         The next () method of iterator class cannot appear twice in the same loop, which will cause the last cursor to point to a null value.

Modification:

         Add a variable to receive the iterator:

    Object a = iterator.next();
    String value = a==null?"":String.valueOf(a);

 

Read More: