Ankur
Ankur

Reputation: 51100

How do you delete null objects (not values) from a list

I have objects of a class Choice which are in a list.

Choice looks like this.

public class Choice extends MorphiaModel{   
    public String name;
    public Double price;
}

Some of them are empty, that is name is "" and price is null.

I want to remove these empty values.

I tried iterating over the list and removing them empty Choice objects, but I got a ConcurrentModificationException then I did this (after implementing equals and hashcode), but it doesn't work, the empty values are still there.

Note: option.choices is a list of Choice objects

Choice emptyChoice = new Choice();
    emptyChoice.name = "";
    emptyChoice.price = null;

    option.choices.remove(emptyChoice);

Upvotes: 1

Views: 825

Answers (2)

Costi Ciudatu
Costi Ciudatu

Reputation: 38195

then I did this (after implementing equals and hashcode), but it doesn't work, the empty values are still there

List.remove() removes only the first element that matches (the one with the lowest index). To remove them all, you could put it in a loop (remove() returns boolean true if it succeeds):

while ( option.choices.remove(emptyElement) );

Upvotes: 2

fivedigit
fivedigit

Reputation: 18682

The ConcurrentModificationException happened because you tried to remove the elements outside of the Iterator iterating over the list.

Something like this works:

Iterator<Choice> iterator = option.choices.iterator(); // or use option.choices.listIterator()

while (iterator.hasNext()) {
    if (emptyChoice.equals(iterator.next())) {
        iterator.remove();
    }
}

Upvotes: 8

Related Questions