The joy of streams

Bertil Muth - Jun 24 '18 - - Dev Community

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .