Sort the map entries after grouping by in a better way (java8)

Viewed 62

I have Progess dto with fields studentId and points. I would like to return a result as sum all of points for each studentId from List<Progress> in descending order of points (students who got most points comes first).

I have implemented it as below but is there a better way do this or do it in a same stream itself? Kindle help.

{
        List<Progress> progresses = xxxx;

        if (Objects.isNull(progresses) || progresses.isEmpty()) return Collections.emptyMap();

        Map<String, Integer> result = progresses
                .stream()
                .collect(Collectors.groupingBy(Progress::getStudentId,
                        //LinkedHashMap::new,
                        Collectors.summingInt(Progress::getPoints)));

        Map<String, Integer> finalResult = new LinkedHashMap<>();
        result
                .entrySet()
                .stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .forEachOrdered(e -> finalResult.put(e.getKey(), e.getValue()));

        return finalResult;
}
1 Answers

You can do it in one Stream chained operation

return progresses
        .stream()
        .collect(groupingBy(Progress::getStudentId, summingInt(Progress::getPoints)))
        .entrySet()
        .stream()
        .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
        .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
Related