Home > Software engineering >  Java Stream collected object in List, shows size as 1 but object is null
Java Stream collected object in List, shows size as 1 but object is null

Time:10-10

I am working on a SpringBoot project, where while testing I was deliberately passing something like this in the request and got a NullPointerException:

{
    "materials": [
        {

        }
    ]
}

I don't want to use @NotNull on materials in the Request Class as the materials field can be null. but when it is not null I want to make sure a few fields are present as based on that I need to validate its value.

final List<Material> materials = materialRequests.getMaterials().stream().map(MaterialRequest::getMaterial).collect(Collectors.toList());

// Throws NullPointerException here
final Set<String> materialIds = materials.stream().map(Material::getUuid).collect(Collectors.toSet()); 

While debugging I saw this:

enter image description here

materials shows it has 1 element however it is null, and due to that, I get a null pointer expectation. How can I put a check here to see whether it is null or not.. and why is the behavior like this?

CodePudding user response:

Filter out null elements from the stream before applying map():

final Set<String> materialIds = materials.stream()
    .filter(Objects::nonNull)
    .map(Material::getUuid)
    .collect(Collectors.toSet());

CodePudding user response:

use .filter() to filter out null values:

final Set<String> materialIds = materials.stream().filter(s -> s != null).map(Material::getUuid).collect(Collectors.toSet()); 
  • Related