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

前端 未结 3 666
无人及你
无人及你 2021-01-11 14:52

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:

相关标签:
3条回答
  • 2021-01-11 15:03
    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.

    0 讨论(0)
  • 2021-01-11 15:07

    You could use:

    list.removeAll(Collections.singleton(new ArrayList<>()));
    
    0 讨论(0)
  • 2021-01-11 15:17

    You could try this as well:

    list.removeIf(p -> p.isEmpty());
    
    0 讨论(0)
提交回复
热议问题