swetha
swetha

Reputation: 111

How to check for any null field of Object in List<Object>?

I have a list of Object passed to a method as below.

Student s = new Student (name,age,branch, year); // student prototype

public void log(List<Student> items) { }

Inside the method, I need to check for any null values in each student object and log that particular attribute which was null and the corresponding student object. Is there a way to check this other than using?:

items.stream().anyMatch(item -> item.getAge() == null ? System.out.println());

In actual scenario, my object contains more than 30 attributes and if any of the attribute is null, I want to log that null attributes and its corresponding object.

Upvotes: 0

Views: 1359

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191743

You're going to have to check each field individually if you want to check them one-by-one and log if they are null.

You could use reflection to iterate over all fields, but I would question the applicability of such a use-case.

Note that primtives like int age cannot be null, so you wouldn't need to check for it. Plus, your usage of anyMatch is incorrect as System.out.println does not return a boolean

Upvotes: 3

Related Questions