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

后端 未结 18 1528
感情败类
感情败类 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:55

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

    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

    0 讨论(0)
  • 2020-11-27 10:56
    List<String> colors = new ArrayList<>(
    Arrays.asList("RED", null, "BLUE", null, "GREEN"));
    // using removeIf() + Objects.isNull()
    colors.removeIf(Objects::isNull);
    
    0 讨论(0)
  • 2020-11-27 10:57

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

    The Objects class has a nonNull Predicate that can be used with filter.

    For example:

    tourists.stream().filter(Objects::nonNull).collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-11-27 11:00

    Similar to @Lithium answer but does not throw a "List may not contain type null" error:

       list.removeAll(Collections.<T>singleton(null));
    
    0 讨论(0)
提交回复
热议问题