如何从列表中删除空列表(Java)

时间:2022-06-30 19:00:28

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:

我搜索过这个,但是它是用其他语言,比如Python或R (?)我在列表中有列表,我想删除空列表。例如:

[ [abc,def], [ghi], [], [], [jkl, mno]]

[[abc,def] [ghi] [], [], [], [jkl, mno]]

I would like:

我想:

[ [abc,def], [ghi], [jkl, mno]]

[[abc,def], [ghi], [jkl, mno]]

How do I remove empty list from a list? Thanks!

如何从列表中删除空列表?谢谢!

3 个解决方案

#1


24  

You could try this as well:

你也可以试试这个:

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

#2


12  

You could use:

您可以使用:

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

#3


11  

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.

上面的代码适用于许多情况,但是它依赖于列表中列表的equals方法实现,所以如果您有如下代码,它将失败。

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.

如果您不担心equals方法的不同实现,您可以使用另一种解决方案。

#1


24  

You could try this as well:

你也可以试试这个:

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

#2


12  

You could use:

您可以使用:

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

#3


11  

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.

上面的代码适用于许多情况,但是它依赖于列表中列表的equals方法实现,所以如果您有如下代码,它将失败。

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.

如果您不担心equals方法的不同实现,您可以使用另一种解决方案。