title: Count non null fields in an object
body: <p>I have a <code>UserProfile</code> class which contains user's data as shown below:</p>
  
  <pre><code>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
  }
  </code></pre>
  
  <p>I need to count non <code>null</code> 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: <code>userId</code>, <code>loginId</code> and <code>displayName</code>.</p>
  
  <p>Simple way would be to use multiple <code>If</code> statements to get the non null field <code>count</code> but it would involve lot of boiler plate code and there is another class <code>Organization</code> for which I need to show completion percentage as well. So I created a utility function as show below:</p>
  
  <pre><code>public static &lt;T, U&gt; int getNotNullFieldCount(T t,
          List&lt;Function&lt;? super T, ? extends U&gt;&gt; functionList) {
      int count = 0;
  
      for (Function&lt;? super T, ? extends U&gt; function : functionList) {
          count += Optional.of(t).map(obj -&gt; function.apply(t) != null ? 1 : 0).get();
      }
  
      return count;
  }
  </code></pre>
  
  <p>And then I call this function as shown below:</p>
  
  <pre><code>List&lt;Function&lt;? super UserProfile, ? extends Object&gt;&gt; functionList = new ArrayList&lt;&gt;();
  functionList.add(UserProfile::getAge);
  functionList.add(UserProfile::getAddress);
  functionList.add(UserProfile::getEmail);
  functionList.add(UserProfile::getContactNumber);
  System.out.println(getNotNullFieldCount(userProfile, functionList));
  </code></pre>
  
  <p>My question is, is this the best way I could count not <code>null</code> fields or I could improve it further. Please suggest.</p>