Reputation: 89
I am trying with this code to replace null values in arraylist. I am getting null values in a tag in my xml file. Values in that tag are coming from arraylist. I want to remove null from tag and put nothing in place of it. My code is something like this:
for(String s:a.getList){
here I setting values in tag by create tag and than appending child nodess using DOM parser.
}
where a=object that contains list
output is like this:
<value>1</value>
<value>2</value>
<value>null</value>
<value>3</value>
<value>4</value>
<value>null</null>
. . .and so on
Expected output:
<value>1</value>
<value>2</value>
<value/>
<value>3</value>
<value>4</value>
<value/>
null should be removed and tag should look something like this
code I am trying is:
for(String s:a.list){
if(s.equals("null")){
s.replace("null","");
my code;
}
Always getting null pointer exception and don't know if this runs what will be output. Please help..
Upvotes: 0
Views: 806
Reputation: 725
The best way to approach using array list is iterate from last to first if you want to remove concurrently.
for (int i = list.size()-1; i >= 0; i--) {
if ("null".equalsIgnoreCase(list.get(i))) {
list.remove(i);
}
}
"null".equalsIgnoreCase(list.get(i)) will avoid null pointer exception
For removing and printing value
for (String str : abc) {
if ("null".equalsIgnoreCase(str)) {
System.out.println("<value/>");
} else {
System.out.println("<value>"+str+"</value>");
}
}
Upvotes: 1
Reputation: 840
To make it clearer
public static void main(String... args) {
ArrayList<String> a = new ArrayList<String>();
a.add("one");
a.add(null);
a.add("two");
a.removeAll(Collections.singleton(null));
for(String value : a) {
System.out.println(value);
}
}
Output
one
two
Upvotes: 0
Reputation: 14572
You are not updating the list, you are creating a new String
instance since String
are immutable. Just set the value you want if the current value is "null"
for(int i = 0; i < list.size(); ++i){
if("null".equals(list.get(i)){
list.set(i, "");
}
}
The condition won't fail for null
value, but if you want to replace those, you need to add the condition because for now, it will only update "null"
.
Upvotes: 1