【问题标题】:Need a equivalent code in java streams for iterating list of Object需要 java 流中的等效代码来迭代对象列表
【发布时间】:2021-10-31 06:55:17
【问题描述】:

谁能帮我处理流等效代码 注意:- 我不能将 studentFinalList 设为“final”

List<Student> studentFinalList=new ArrayList<>();
for (Student ep:StudentList) {
    if (StringUtils.isBlank(ep.getName()) && ep.getName() == null) {
        studentFinalList.add(ep);
    }
    else if (StringUtils.isNotBlank(ep.getName()) && 
        !ep.getName().equals("") && ep.getName() != null) {
        if (sIdList.contains(ep.getId())) {
            studentFinalList.add(ep);
        }
    }
}

【问题讨论】:

  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: java arraylist java-stream


【解决方案1】:

代码中的某些条件似乎是多余的,可以去掉而不影响逻辑:

  • StringUtils.isBlank(ep.getName()) &amp;&amp; ep.getName() == null 可以缩短为 ep.getName() == null - 因为 StringUtils.isBlank 会检查 null、空或纯空格字符串
  • StringUtils.isNotBlank(ep.getName()) &amp;&amp; !ep.getName().equals("") &amp;&amp; ep.getName() != null - 没有必要检查 !name.equals("")null 所以只有 StringUtils.isNotBlank(ep.getName()) 就足够了。

接下来,应将 id 列表 sIdList 转换为集合以方便查找 id(集合中的 O(1) 而不是列表中的 O(N))。

因此,代码可以简化为:

Set<String> sIdSet = new HashSet<>(sIdList);
List<Student> studentFinalList = studentList
    .stream()
    .filter(ep -> ep.getName() == null 
        || (!StringUtils.isBlank(ep.getName()) && sIdSet.contains(ep.getId()))
    )
    .collect(Collectors.toList());

【讨论】:

  • no 有时“名称”可能包含空白值或有时为 null,因此我们需要验证两者
  • @TechTravellers, Apache Commons StringUtils::isBlank 检查 CharSequence 是否为空 ("")、null 或仅空格。 因此检查字符串 isBlank AND同时等于null。如果您的意思是isBlank AND null - 只需要空检查;如果你的意思是isBlank OR null - 只打电话给isBlank
【解决方案2】:

您可以将所有 if 语句放在一个 filter 中:

List<Student> studentFinalList = studentList.stream()
        .filter(ep -> (StringUtils.isBlank(ep.getName()) && ep.ep.getName() == null) ||
                  (StringUtils.isNotBlank(ep.getName()) && !ep.getName().equals("") &&
                          ep.getName() != null && sIdList.contains(ep.getId())))
          .collect(Collectors.toList());

虽然我建议仔细检查您提交的代码,因为我怀疑它包含一些错误,例如ep.ep.getName()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    相关资源
    最近更新 更多