gpt4 book ai didi

java - 计算对象中的非空字段

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:19:50 24 4
gpt4 key购买 nike

我有一个包含用户数据的 UserProfile 类,如下所示:

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 字段进行计数,以显示用户填写了配置文件的百分比。还有一些我不想在百分比计算中考虑的字段,例如:userIdloginIddisplayName

简单的方法是使用多个 If 语句来获取非空字段 count 但它会涉及很多样板代码并且还有另一个类 我还需要显示完成百分比的组织。所以我创建了一个实用函数,如下所示:

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;
}

然后我调用这个函数,如下所示:

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 字段的最佳方式,或者我可以进一步改进它。请提出建议。

最佳答案

您可以通过在给定的函数列表上创建一个 Stream 来简化您的代码:

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 字段的计数。每个函数都映射到将其应用于给定对象的结果,并且使用谓词 Objects::nonNull 过滤掉 null 字段.

关于java - 计算对象中的非空字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36912914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com