首页 > 解决方案 > 针对 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(如果是字符串)?(或者更好的方法?)

标签: java

解决方案


这是一些代码,它显示了使用 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);

推荐阅读