简体   繁体   中英

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. I am confused when I should use map or filter in this situation

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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