Sudhir Singh Sudhir Singh - 2 years ago 62
Java Question

Count non null fields in an object

I have a

class which contains user's data as shown below:

class UserProfile {

private String userId;
private String displayName;
private String loginId;
private String role;
private String orgId;
private String email;
private String contactNumber;
private Integer age;
private String address;

// few more fields ...

// getter and setter

I need to count non
fields to show how much percentage of the profile has been filled by the user. Also there are few fields which I do not want to consider in percentage calculation like:

Simple way would be to use multiple
statements to get the non null field
but it would involve lot of boiler plate code and there is another class
for which I need to show completion percentage as well. So I created a utility function as show below:

public static <T, U> int getNotNullFieldCount(T t,
List<Function<? super T, ? extends U>> functionList) {
int count = 0;

for (Function<? super T, ? extends U> function : functionList) {
count += Optional.of(t).map(obj -> function.apply(t) != null ? 1 : 0).get();

return count;

And then I call this function as shown below:

List<Function<? super UserProfile, ? extends Object>> functionList = new ArrayList<>();
System.out.println(getNotNullFieldCount(userProfile, functionList));

My question is, is this the best way I could count not
fields or I could improve it further. Please suggest.

Answer Source

You can simply a lot your code by creating a Stream over the given list of functions:

public static <T> long getNonNullFieldCount(T t, List<Function<? super T, ?>> functionList) {
    return -> f.apply(t)).filter(Objects::nonNull).count();

This will return the count of non-null fields returned by each function. Each function is mapped to the result of applying it to the given object and null fields are filtered out with the predicate Objects::nonNull.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download