Question

Here's what I am doing: I have an event from an RSS feed that is telling me that a Ticket was edited. To get the changes made to that ticket, I have to call a REST service.

So I wanted to do it with a more compact, functional approach, but it just turned into a bunch of craziness. When in fact, the straight old style Java is this simple:

/**
 * Since the primary interest is in what has been changed, we focus on getting changes
 * often and pushing them into the appropriate channels.
 *
 * @return changes made since we last checked
 */
public List<ProcessEventChange> getLatestChanges(){
    List<ProcessEventChange> recentChanges = new ArrayList<>();
    List<ProcessEvent> latestEvents = getLatestEvents();
    for (ProcessEvent event : latestEvents){
        recentChanges.addAll(getChanges(event));
    }
    return recentChanges;
}

There were a couple questions on here that related to this that did not seem to have straightforward answers, I am asking this question so that there's a very specific example and the question is crystal clear: is it work reworking this with streams and if so how?

If streams are not good for things like this they are really not good for much. The reason I say that is this is a very common requirement: that some piece of data be enriched with more information from another source.

Was it helpful?

Solution

What you need is flatMap, which can map a single ProcessEvent object of the input list to multiple ProcessEventChange objects, and flatten all those objects to a single Stream of ProcessEventChange.

List<ProcessEventChange> recentChanges = getLatestEvents().
         stream().
         flatMap(e -> getChanges(e).stream()).
         collect(Collectors.toList());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top