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]
removeAll(Arrays. asList(null,"")); This will remove all elements that are null or equals to "" in your List .
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.
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]
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(""));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With