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
List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", null, "How"));
System.out.println(list);
list.removeAll(Arrays.asList("", null));
System.out.println(list);
Output:
[, Hi, null, How]
[Hi, How]
Its a very late answer, but you can also use the Collections.singleton
:
List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", null, "How"));
list.removeAll(Collections.singleton(null));
list.removeAll(Collections.singleton(""));
private List cleanInputs(String[] inputArray) {
List<String> result = new ArrayList<String>(inputArray.length);
for (String input : inputArray) {
if (input != null) {
String str = input.trim();
if (!str.isEmpty()) {
result.add(str);
}
}
}
return result;
}
If you were asking how to remove the empty strings, you can do it like this (where l
is an ArrayList<String>
) - this removes all null
references and strings of length 0:
Iterator<String> i = l.iterator();
while (i.hasNext())
{
String s = i.next();
if (s == null || s.isEmpty())
{
i.remove();
}
}
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.
If you get UnsupportedOperationException
from using one of ther answer above and your List
is created from Arrays.asList()
, it is because you can't edit such List
.
To fix, wrap the Arrays.asList()
inside new LinkedList<String>()
:
List<String> list = new LinkedList<String>(Arrays.asList(split));
Source is from this answer.
public static void listRemove() {
List<String> list = Arrays.asList("", "Hi", "", "How", "are", "you");
List<String> result = new ArrayList<String>();
for (String str : list) {
if (str != null && !str.isEmpty()) {
result.add(str);
}
}
System.out.println(result);
}