How to remove empty elements from a List of Strings in Java

2 Answers

0 votes
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MyClass {
    public static void main(String args[]) {
        try {
            List<String> list = new ArrayList<String>(Arrays.asList("", "c", "", "", "c++"));
            
            list.removeAll(Arrays.asList(""));
            
            System.out.println(list);
 
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
}

  
/*
                 
run:
    
[c, c++]
        
*/

 



answered Dec 15, 2016 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<String>(Arrays.asList("", "java", "c", null, ""));
          
        System.out.println(list);
          
        list.removeAll(Arrays.asList("", null));
          
        System.out.println(list);
    }
}
  
  
  
  
/*
run:
  
[, java, c, null, ]
[java, c]
  
*/

 



answered Apr 21, 2024 by avibootz

Related questions

1 answer 203 views
1 answer 116 views
1 answer 209 views
1 answer 187 views
1 answer 177 views
...