Tim Tim
Tim Tim

Reputation: 23

Lambda with two streams

Can I do this without doing two separate streams and without temporarily storing id's and statuses in a HashMap?

SaveStatus saveStatus = saveService.save(input);
Map<Long, SaveStatus> savedStatuses = new HashMap<>();
saveStatus.getSaveStatusResults()
    .stream()
    .forEach(s -> savedStatuses.put(s.getId(), s.getSavedStatus()));

objectToUpdateWithNewStatuses.getSaveInstructions()
    .stream()
    .map(SaveInstruction::getTransaction)
    .forEach(t -> t.setSaveStatus(savedStatuses.get(t.getId())));

Upvotes: 2

Views: 95

Answers (1)

davidxxx
davidxxx

Reputation: 131346

Using two distinct streams makes sense here!

The second stream doesn't take as input/source the map collected from the first stream, it needs that to perform fast retrieval.

But you could improve the first stream in this way:

Map<Long, SaveStatus> savedStatuses = 
saveStatus.getSaveStatusResults()
    .stream()
    .collect(toMap(SaveStatusResult::getId, SaveStatusResult::getSavedStatus));

The method references used suppose that SaveStatus.getSaveStatusResults() returns an Collection of SaveStatusResult.

And keep the second stream as it is defined.

Upvotes: 2

Related Questions