Created
February 10, 2016 02:48
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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