计算对象中的非空字段 [英] Count non null fields in an object
问题描述
我有一个 UserProfile
类,其中包含用户数据,如下所示:
I have a UserProfile
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
}
我需要计算非 null
字段,以显示用户填充了多少百分比的配置文件。还有一些我不想在百分比计算中考虑的字段,如: userId
, loginId
和 displayName
。
I need to count non null
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: userId
, loginId
and displayName
.
简单的方法是使用多个 If
语句来获取非空字段计数
但它会涉及大量的锅炉板代码,并且还有另一个类组织
还需要显示完成百分比。所以我创建了一个实用函数,如下所示:
Simple way would be to use multiple If
statements to get the non null field count
but it would involve lot of boiler plate code and there is another class Organization
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<>();
functionList.add(UserProfile::getAge);
functionList.add(UserProfile::getAddress);
functionList.add(UserProfile::getEmail);
functionList.add(UserProfile::getContactNumber);
System.out.println(getNotNullFieldCount(userProfile, functionList));
我的问题是,这是我算不上的最佳方式 null
字段或我可以进一步改进它。请建议。
My question is, is this the best way I could count not null
fields or I could improve it further. Please suggest.
推荐答案
您可以通过在给定的函数列表上创建Stream来简单地编写代码:
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();
}
这将返回非 null <的计数/ code>每个函数返回的字段。每个函数都映射到将其应用于给定对象的结果,并使用谓词 null
字段/javase/8/docs/api/java/util/Objects.html#nonNull-java.lang.Object-\"rel =nofollow> Objects :: nonNull
。
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
.
这篇关于计算对象中的非空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!