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

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

    Using Java 8 this can be performed in various ways using streams, parallel streams and removeIf method:

    List stringList = new ArrayList<>(Arrays.asList(null, "A", "B", null, "C", null));
    List listWithoutNulls1 = stringList.stream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList()); //[A,B,C]
    List 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.

提交回复
热议问题