Count non null fields in an object

后端 未结 1 739
-上瘾入骨i
-上瘾入骨i 2021-01-02 17:01

I have a UserProfile class which contains user\'s data as shown below:

class UserProfile {

  private String userId;
  private String displayNam         


        
相关标签:
1条回答
  • 2021-01-02 17:25

    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 functionList.stream().map(f -> 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.

    0 讨论(0)
提交回复
热议问题