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;
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.
source share