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

大憨熊 提交于 2019-12-19 05:21:32

问题


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!


回答1:


You could try this as well:

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



回答2:


You could use:

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



回答3:


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.



来源:https://stackoverflow.com/questions/31196620/how-to-remove-an-empty-list-from-a-list-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!