I try with a loop like that
// ArrayList tourists
for (Tourist t : tourists) {
if (t != null) {
t.setId(idForm);
}
}
I used the stream interface together with the stream operation collect and a helper-method to generate an new list.
tourists.stream().filter(this::isNotNull).collect(Collectors.toList());
private <T> boolean isNotNull(final T item) {
return item != null;
}
Using Java 8, you can do this using stream()
and filter()
tourists = tourists.stream().filter(t -> t != null).collect(Collectors.toList())
or
tourists = tourists.stream().filter(Objects::nonNull).collect(Collectors.toList())
For more info : Java 8 - Streams
List<String> colors = new ArrayList<>(
Arrays.asList("RED", null, "BLUE", null, "GREEN"));
// using removeIf() + Objects.isNull()
colors.removeIf(Objects::isNull);
This is easy way to remove default null values from arraylist
tourists.removeAll(Arrays.asList(null));
otherwise String value "null" remove from arraylist
tourists.removeAll(Arrays.asList("null"));
The Objects
class has a nonNull
Predicate
that can be used with filter
.
For example:
tourists.stream().filter(Objects::nonNull).collect(Collectors.toList());
Similar to @Lithium answer but does not throw a "List may not contain type null" error:
list.removeAll(Collections.<T>singleton(null));