Reputation: 357
I have searched for this but it's in other languages like Python or R (?). I have lists inside a list and I would like to remove the empty list. For example:
[ [abc,def], [ghi], [], [], [jkl, mno]]
I would like:
[ [abc,def], [ghi], [jkl, mno]]
How do I remove empty list from a list? Thanks!
Upvotes: 12
Views: 6978
Reputation: 1171
list.removeAll(Collections.singleton(new ArrayList<>()));
The code above works fine for many cases but it's dependent on the equals method implementation of the List in the list so if you have something like the code below it will fail.
public class AnotherList extends ArrayList<String> {
@Override
public boolean equals(Object o) {
return o instanceof AnotherList && super.equals(o);
}
}
List<List<String>> list = new ArrayList<>();
list.add(Arrays.asList("abc", "def"));
list.add(Arrays.asList("ghi"));
list.add(new ArrayList<String>());
list.add(new ArrayList<String>());
list.add(new AnotherList());
list.add(null);
list.add(Arrays.asList("jkl", "mno"));
A solution is:
list.removeIf(x -> x != null && x.isEmpty());
If you have no worry about a different implementation of equals method you can use the other solution.
Upvotes: 11
Reputation: 2667
You could use:
list.removeAll(Collections.singleton(new ArrayList<>()));
Upvotes: 12