java - 针对 boolean 或 notnull / empty 针对字符串测试 true
问题描述
为了获取具有 True 或 NotNull/NotEmpty 值的部分的名称,我正在从以下 Java 对象创建一个 Map,然后对其进行迭代。
public class Assessment {
private Boolean section1Checkbox1;
private Boolean section1Checkbox2;
private Boolean section1Comments;
private Boolean section2Checkbox1;
private Boolean section2Checkbox2;
private Boolean section2Comments;
more sections.....
我已将对象转换为 Map,然后对其进行迭代:
Map<String, Object> map = oMapper.convertValue(needsAssessment, Map.class);
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
if (pair.getValue()==true||NotNull) {
// Get Section Name
String[] sectionName = pair.getKey().toString().split("(?=\\p{Upper})");
System.out.println(sectionName[0]);
}
}
pair.getValue() 测试有错误:
有没有办法在一个语句中测试 true(如果是布尔值)和 NotNull 或 Empty(如果是字符串)?(或者更好的方法?)
解决方案
这是一些代码,它显示了使用 lambdas 和流进行集合过滤和转换的更惯用的 Java 8+ 方式:
Map<String, Object> map = oMapper.convertValue(assessment, Map.class);
map.entrySet()
// stream all entries
.stream()
// filter by value being TRUE (this is null safe)
.filter((e) -> Boolean.TRUE.equals(e.getValue()))
// transform entry to key split by regex
.map(e -> e.getKey().split("(?=\\p{Upper})"))
// transform to first array item
.map(a -> a[0])
// print
.forEach(System.out::println);
推荐阅读
- python - 使用 xcom 返回值遍历 python 字典列表
- reactjs - 如何在反应中将文件上传到后端
- python - 为什么 python 脚本从本地 IP 运行,但在 IIS 配置 IP 时出错?
- vb6 - 在 VB6 中从 WebBrowser 中捕获双击
- templates - 如何在拣货单上显示套件项目的组件项目的自定义字段 - Netsuite
- python - 在列中删除带有 Type(int) 的值
- angular - 如何在 Angular 中以一种方法订阅 httpRequest 和 observable
- sql-server - 如何将 SQL Server 函数 (T-SQL) 转换为 Oracle 的 PL/SQL 函数?
- javascript - ReactJS 文本输入
- php - 邮件发送给数据库的第一个学生 n 次