Retrieve fixed number of entries around an entry in a map sorted by values

匆匆过客 提交于 2019-12-05 16:56:45

Stream#limit shall help you restrict finding the top N(5) users on the reversed list you've created and further you can map List> using the values and collect a List<Entry> from it finally as:

return leaderBoardUserEntryMap.entrySet().stream()
            .sorted(Map.Entry.comparingByValue(Comparator.comparing(Entry::getScore, Integer::compare).reversed()))
            .limit(5).map(Map.Entry::getValue).collect(Collectors.toList());

Edit: thanks to @Yogesh for the use case

say there are 100 users, and the user that is being searched is at 93. List should return 91, 92, 93, 94, 95. This solution will return 1, 2, 3, 4, 5

Since the use case is to have a subList around the current entry, this could be modified as:

List<GameEntry> selectedEntries =  leaderBoardUserEntryMap.entrySet().stream()
            .sorted(Map.Entry.comparingByValue(Comparator.comparing(GameEntry::getScore, Integer::compare)
                    .reversed())).map(Map.Entry::getValue).collect(Collectors.toList());

int indexOfnewEntry = selectedEntries.indexOf(leaderBoardUserEntryMap.get(uid));
return  selectedEntries.subList(indexOfnewEntry-2,indexOfnewEntry+2);

Edit 2:

The indexOfnewEntry and +- 2 can cause IndexOutOfBoundsException, guarding against it seems a bit tedious, any optimal ways here?

Since the index of the entry might vary on the score, and the subList access further also relies on the number of output desired before/after it. Guarding shall be a better option than any other. Also what could be considered is a customSubList implementation which could internally check your collection type. How to use subList() explains this with top voted answers. I specifically liked this one though :

dataList.subList(Math.max(0, first), Math.min(dataList.size(), last) );

Will using parallelStream() cause problems?

Unless there are any synchronized blocks executed that might alter and make concurrent updates to the stream it wouldn't cause any problems.

But you should know when to use parallel stream - Should I always use a parallel stream when possible?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!