The joy of streams

Recently, I have written a class that looked roughly like this:

public class Requirement { ...
    public Requirement(...) { ...
    }
    public When getWhen() { ...
    }
    public Event getEvent() {...
    }
    public SystemReaction getSystemReaction() {...
    }
}

Enter fullscreen mode Exit fullscreen mode

I had a list of Requirement instances. Now, I needed the set of Event instances that was referenced by at least one Requirement. An Event instance could also be null.

In Java before Java 8, I would have done the following:
a) Create an empty HashSet
b) Iterate over the list of Requirement instances
c) For each Requirement instance, check if getEvent() returns null
d) If it does not return null, add the event to the HashSet

Starting with Java 8, you can use streams to accomplish this task in a one-liner:

Set<Event> events = requirements.stream().map(req -> req.getEvent())
  .filter(event -> event != null).collect(Collectors.toSet());

Enter fullscreen mode Exit fullscreen mode

To find out more about streams, check out this tutorial.

原文链接:The joy of streams

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容