How to efficiently remove all null elements from a ArrayList or String Array?
Try:
tourists.removeAll(Collections.singleton(null));
Read the Java API. The code will throw java.lang.UnsupportedOperationException
for immutable lists (such as created with Arrays.asList
); see this answer for more details.
Remove null elements from list
This should work:
list.removeAll(Collections.singleton(null));
Java - Remove null from list of Objects
Mutable list
You can use List::removeIf
with a predicate detecting null
items.
List<Object[]> mutableList = new ArrayList<>(Arrays.asList(
new Object[] {},
null,
new Object[] {}));
mutableList.removeIf(Objects::isNull);
Immutable list
In this case you have to use Stream API or a for-loop to find non-null elements and add them to a new list.
List<Object[]> immutableList = Arrays.asList(
new Object[] {},
null,
new Object[] {});
List<Object[]> newList = immutableList.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
Remove Null Value from String array in java
If you want to avoid fencepost errors and avoid moving and deleting items in an array, here is a somewhat verbose solution that uses List
:
import java.util.ArrayList;
import java.util.List;
public class RemoveNullValue {
public static void main( String args[] ) {
String[] firstArray = {"test1", "", "test2", "test4", "", null};
List<String> list = new ArrayList<String>();
for(String s : firstArray) {
if(s != null && s.length() > 0) {
list.add(s);
}
}
firstArray = list.toArray(new String[list.size()]);
}
}
Added null
to show the difference between an empty String instance (""
) and null
.
Since this answer is around 4.5 years old, I'm adding a Java 8 example:
import java.util.Arrays;
import java.util.stream.Collectors;
public class RemoveNullValue {
public static void main( String args[] ) {
String[] firstArray = {"test1", "", "test2", "test4", "", null};
firstArray = Arrays.stream(firstArray)
.filter(s -> (s != null && s.length() > 0))
.toArray(String[]::new);
}
}
Related Topics
Changing Shape of Single Point in Jfreechart Xyplot
Calling Static Method from Another Java Class
Foreach VS Foreachordered in Java 8 Stream
Java Equivalent of Unsigned Long Long
Splitting a CSV File with Quotes as Text-Delimiter Using String.Split()
Java.Lang.Nosuchmethoderror in Flink
Retrofit 2.0 How to Get Deserialised Error Response.Body
What Is the Most Accurate Encoding Detector
Getting Active Window Information in Java
Converting String to Date Using Simpledateformat Is Returning Random Date
Best Language to Parse Extremely Large Excel 2007 Files
How to Zip a Folder Itself Using Java
How to Redirect Processbuilder's Output to a String
How to Find Repeated Characters with a Regex in Java