Count nonzero fields in an object

I have a UserProfile class that contains user 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- null fields to show how many percent of the profile has been completed by the user. There are also several fields that I do not want to consider in percentage calculation, for example: userId , loginId and displayName .

A simple way would be to use several If statements to get a non-empty count field, but this is due to a lot of boiler plate code, and there is another Organization class for which I also need to show the completion percentage, So I created a utility function, as shown 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<>(); functionList.add(UserProfile::getAge); functionList.add(UserProfile::getAddress); functionList.add(UserProfile::getEmail); functionList.add(UserProfile::getContactNumber); System.out.println(getNotNullFieldCount(userProfile, functionList)); 

My question is, is this the best way that I could consider non null , or I could improve it further. Please suggest.

+5
source share
1 answer

You can simply add your code by creating Stream over this list of functions:

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

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

+6
source

All Articles