I try with a loop like that
// ArrayList tourists
for (Tourist t : tourists) {
if (t != null) {
t.setId(idForm);
}
}
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.
I played around with this and found out that trimToSize() seems to work. I am working on the Android platform so it might be different.
for (Iterator<Tourist> itr = tourists.iterator(); itr.hasNext();) {
if (itr.next() == null) { itr.remove(); }
}
If you prefer immutable data objects, or if you just dont want to be destructive to the input list, you can use Guava's predicates.
ImmutableList.copyOf(Iterables.filter(tourists, Predicates.notNull()))
As of 2015, this is the best way (Java 8):
tourists.removeIf(Objects::isNull);
Note: This code will throw java.lang.UnsupportedOperationException
for fixed-size lists (such as created with Arrays.asList), including immutable lists.
Using Java 8 this can be performed in various ways using streams, parallel streams and removeIf
method:
List<String> stringList = new ArrayList<>(Arrays.asList(null, "A", "B", null, "C", null));
List<String> listWithoutNulls1 = stringList.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList()); //[A,B,C]
List<String> listWithoutNulls2 = stringList.parallelStream()
.filter(Objects::nonNull)
.collect(Collectors.toList()); //[A,B,C]
stringList.removeIf(Objects::isNull); //[A,B,C]
The parallel stream will make use of available processors and will speed up the process for reasonable sized lists. It is always advisable to benchmark before using streams.