sw2
sw2

Reputation: 357

How to remove an empty list from a list (Java)

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

Answers (3)

Micho
Micho

Reputation: 3963

You could try this as well:

list.removeIf(p -> p.isEmpty());

Upvotes: 27

Rodolfo
Rodolfo

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

Alex S. Diaz
Alex S. Diaz

Reputation: 2667

You could use:

list.removeAll(Collections.singleton(new ArrayList<>()));

Upvotes: 12

Related Questions