2

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.

1 Answer 1

4

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());
Sign up to request clarification or add additional context in comments.

2 Comments

I looked at flatMap but did not have the .stream() call on the end of getChanges(e). Will try that.
Nice. How on earth can the docs not have an example of doing this? Maybe I missed it, will look again. Meantime, test passes. Thanks Eran.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.