簡體   English   中英

在這種情況下我應該如何使用流

[英]How should I use streams in this situation

我是在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;
}
  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)並根據其狀態過濾它們,然后減少列表保留最舊的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM