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:
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.
You could use:
list.removeAll(Collections.singleton(new ArrayList<>()));
You could try this as well:
list.removeIf(p -> p.isEmpty());