Skip to content

Instantly share code, notes, and snippets.

@Randgalt
Created February 10, 2016 02:48
Show Gist options
  • Save Randgalt/f9a2ac5ae00c7e704ca5 to your computer and use it in GitHub Desktop.
Save Randgalt/f9a2ac5ae00c7e704ca5 to your computer and use it in GitHub Desktop.
Given a list of votes on a location, return the most recent vote for each location
public List<LocationVote> getMaxTimestampAscending(List<LocationVote> locationVotesSince)
{
// map/reduce to max timestamp for a location
Map<LocationKey, Optional<Long>> locationToTimestampDesc = locationVotesSince
.stream()
.collect(
Collectors.groupingBy(
LocationVote::getLocationKey,
Collectors.mapping(LocationVote::getTimestampUtcEpochMilli, Collectors.maxBy(Comparator.reverseOrder())))
)
;
// convert to list of locations that were mapped sorted by timestamp ascending
return locationVotesSince.stream()
.filter(vote -> {
Optional<Long> time = locationToTimestampDesc.getOrDefault(vote.getLocationKey(), Optional.empty());
return time.isPresent() && (time.get() == vote.getTimestampUtcEpochMilli());
})
.sorted(Comparator.comparingLong(LocationVote::getTimestampUtcEpochMilli))
.collect(Collectors.toList());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment