简体   繁体   English

在这种情况下我应该如何使用流

[英]How should I use streams in this situation

I am new using stream in java and would like to know if there exists a way to optimize this code.我是在java使用stream新手,想知道是否存在优化此代码的方法。 I am confused when I should use map or filter in this situation在这种情况下我什么时候应该使用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;
}
  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;

This will get all the Persons that have Activities, stream all the Activity's (flatMap) and filter those on their status and then reduce the list keeping the oldest one这将获得所有拥有活动的人员,流式传输所有活动(flatMap)并根据其状态过滤它们,然后减少列表保留最旧的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM