1

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?

3 Answers 3

3

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());
0
2

use .filter() to filter out null values:

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

You can filter the materials in the collection stage, before id`s collecting:

final List<Material> materials = materialRequests.getMaterials().stream()
.map(MaterialRequest::getMaterial)
.filter(m -> m.getUuid != null)
.collect(Collectors.toList());

Not the answer you're looking for? Browse other questions tagged or ask your own question.