【问题标题】:How should I use streams in this situation在这种情况下我应该如何使用流
【发布时间】:2020-03-04 19:13:56
【问题描述】:

我是在java 中使用stream 的新手,想知道是否存在优化此代码的方法。在这种情况下我应该使用map 或过滤时感到困惑

public Active get(List<Person> personList){
        Active a = null;
        for(Person person:personList){
            if(person.getActives() != null && !person.getActives().isEmpty()){
                for(Active active: person.getActives()){
                    if(active.getStatus().equals(SOME_VALUE)){
                        if (a == null || a.getDueDate().isAfter(active.getDueDate())) {
                            a = active;
                        }
                    }
                }
            }
        }
        return a;
}

【问题讨论】:

  • 那么,将其转化为流操作的实际问题是什么?

标签: java list java-stream


【解决方案1】:
  Active a = personList.stream()
         .filter(person -> person.getActives() != null && !person.getActives().isEmpty()
         .flatMap(person -> person.getActivities())
         .filter(activity -> active.getStatus().equals(SOME_VALUE))
         .reduce(null, (pos_a, activity) -> 
           (pos_a == null || a.getDueDate().isAfter(active.getDueDate()))? activity: pos_a)
    return a;

这将获取所有拥有活动的人员,流式传输所有活动 (flatMap) 并根据其状态过滤它们,然后减少列表以保留最旧的人

【讨论】:

  • reduce(null, …) 在没有元素时会抛出异常。更好地使用min(Comparator.comparing(Active::getDueDate)).orElse(null)
猜你喜欢
  • 1970-01-01
  • 2011-01-17
  • 2022-07-22
  • 1970-01-01
  • 2013-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多