How to remove all null elements from a ArrayList or String Array?

后端 未结 18 1569
感情败类
感情败类 2020-11-27 10:26

I try with a loop like that

// ArrayList tourists

for (Tourist t : tourists) {
    if (t != null) {     
        t.setId(idForm); 
    }   
}
相关标签:
18条回答
  • 2020-11-27 10:37

    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.

    0 讨论(0)
  • 2020-11-27 10:39

    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.

    0 讨论(0)
  • 2020-11-27 10:41
     for (Iterator<Tourist> itr = tourists.iterator(); itr.hasNext();) {
          if (itr.next() == null) { itr.remove(); }
     }
    
    0 讨论(0)
  • 2020-11-27 10:42

    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()))
    
    0 讨论(0)
  • 2020-11-27 10:43

    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.

    0 讨论(0)
  • 2020-11-27 10:44

    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.

    0 讨论(0)
提交回复
热议问题