Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, remove empty elements from a list of Strings

Tags:

java

arrays

In Java, I have an ArrayList of Strings like:

[,Hi, ,How,are,you] 

I want to remove the null and empty elements, how to change it so it is like this:

[Hi,How,are,you] 
like image 457
Niranjan Kumar Avatar asked Apr 02 '11 02:04

Niranjan Kumar


People also ask

How do you remove blank space from an ArrayList?

removeAll(Arrays. asList(null,"")); This will remove all elements that are null or equals to "" in your List .

How do you trim a string list in Java?

The trimToSize() method of ArrayList in Java trims the capacity of an ArrayList instance to be the list's current size. This method is used to trim an ArrayList instance to the number of elements it contains. Parameter: It does not accepts any parameter. Return Value: It does not returns any value.


2 Answers

List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", null, "How")); System.out.println(list); list.removeAll(Arrays.asList("", null)); System.out.println(list); 

Output:

[, Hi, null, How] [Hi, How] 
like image 112
lukastymo Avatar answered Sep 16 '22 16:09

lukastymo


Its a very late answer, but you can also use the Collections.singleton:

List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", null, "How")); list.removeAll(Collections.singleton(null)); list.removeAll(Collections.singleton("")); 
like image 27
tokhi Avatar answered Sep 20 '22 16:09

tokhi