如何使用 Java 8 流从 MongoDB 文档列表中找到每次使用的最低分数

How to find the minimum score of each use from a list of MongoDB documents using Java 8 stream

假设我在列表中收集了以下 MongoDB 个文档,

List<Document> all

{ "student_id" : 0, "score" : 14.8504 }
{ "student_id" : 0, "score" : 63.98403 }
{ "student_id" : 1, "score" : 21.33265 }
{ "student_id" : 1, "score" : 44.31668 }
{ "student_id" : 2, "score" : 60.9750 }
{ "student_id" : 2, "score" : 97.75888 }
{ "student_id" : 3, "score" : 50.81575 }

我想使用 Java 8 流和 lambda 表达式将每个用户的最低分数提取到地图中。期望的结果是

{0=14.8504, 1=21.33265, 2=60.9750, 3=50.81575}

下面的作品,不过,似乎有点太复杂了。有没有更简单的方法?

Map<Integer, Double> result = all.stream().
    flatMap(d -> Collections.singletonMap(d.getInteger("student_id"), 
        d.getDouble("score")).entrySet().stream()).
    collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, Math::min));

提前致谢。

收集器实用程序 class 中的 groupingBy 是专门为此任务设计的,因此您应该这样做

Map<Integer, Double> maxScoreByStudentId = this.documents.stream()
            .collect(Collectors.groupingBy(Document::getStudentId, Collectors.collectingAndThen(
                    Collectors.minBy(Comparator.comparingDouble(Document::getScore)), d -> d.get().getScore())));
  1. groupingBy 以Document::getStudentId为键构造一个Map。
  2. collectingAndThen 做了两件事:

    2.1 使用 minBy(Comparator.comparingDouble(Document::getScore)) 计算每个组的最小分数的文档。请注意,minBy returns 是一个 Optional

    2.2 然后用 lambda d -> d.get().getScore() 提取分数。作为 minBy return 一个 Optional,有必要用 d.get

  3. 提取它的值