In Java, remove empty elements from a list of Strings

前端 未结 11 2392
余生分开走
余生分开走 2020-12-01 06:05

In Java, I have an ArrayList of Strings like:

[,Hi, ,How,are,you]

I want to remove the null and empty elements, how to change it so it is l

11条回答
  •  攒了一身酷
    2020-12-01 06:31

    1. If you were asking how to remove the empty strings, you can do it like this (where l is an ArrayList) - this removes all null references and strings of length 0:

      Iterator i = l.iterator();
      while (i.hasNext())
      {
          String s = i.next();
          if (s == null || s.isEmpty())
          {
              i.remove();
          }
      }
      
    2. Don't confuse an ArrayList with arrays, an ArrayList is a dynamic data-structure that resizes according to it's contents. If you use the code above, you don't have to do anything to get the result as you've described it -if your ArrayList was ["","Hi","","How","are","you"], after removing as above, it's going to be exactly what you need - ["Hi","How","are","you"].

      However, if you must have a 'sanitized' copy of the original list (while leaving the original as it is) and by 'store it back' you meant 'make a copy', then krmby's code in the other answer will serve you just fine.

提交回复
热议问题