How to remove all the null elements from a list in Java

3 Answers

0 votes
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
  
public class MyClass {
    public static void main(String args[]) {
        List<String> list = new ArrayList<>(Arrays.asList("java", null, "c++", null, "python")); 
  
        System.out.println(list); 
  
        while (list.remove(null)) {} 
  
        System.out.println(list); 
    }
}



/*
run:

[java, null, c++, null, python]
[java, c++, python]

*/

 



answered May 5, 2020 by avibootz
edited Apr 21, 2024 by avibootz
0 votes
import java.util.Arrays;
import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
  
public class MyClass {
    public static void main(String args[]) {
       List<String> list = new ArrayList<>(Arrays.asList("java", null, "c++", null, "python")); 
   
        System.out.println(list); 
   
        list.removeAll(Collections.singletonList(null)); 
   
        System.out.println(list); 
    }
}
 
 
 
/*
run:
 
[java, null, c++, null, python]
[java, c++, python]
 
*/

 



answered May 5, 2020 by avibootz
edited Apr 21, 2024 by avibootz
0 votes
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
  
public class MyClass {
    public static void main(String args[]) {
       List<String> list = new ArrayList<>(Arrays.asList("java", null, "c++", null, "python")); 
   
        System.out.println(list); 
   
        list.removeAll(Arrays.asList(null, ""));
   
        System.out.println(list); 
    }
}
 
 
 
/*
run:
 
[java, null, c++, null, python]
[java, c++, python]
 
*/

 



answered Apr 21, 2024 by avibootz

Related questions

1 answer 154 views
1 answer 140 views
2 answers 214 views
1 answer 160 views
...