当前位置: 首页 > 面试题库 >

流-按属性和最大值收集

姬锐
2023-03-14
问题内容

给定以下课程(针对问题的简化):

public static class Match {

  private final String type;
  private final int score;

  public Match(String type, int score) {
    this.type = type;
    this.score = score;
  }

  public String getType() {
    return type;
  }

  public int getScore() {
    return score;
  }
}

我有一个Stream<Match>包含该类的多个实例的实例,同一类型出现多次,但得分不同:

Stream.of(new Match("A", 1), new Match("A", 2), new Match("A", 4), new Match("A", 10),
          new Match("B", 3), new Match("B", 6), new Match("B", 12),
          new Match("C", 1));

现在,我想收集流,以便结果List<Match>仅包含每种类型得分最高的实例。

我尝试了什么

以下代码可以正常工作,但是我不确定它是否是“最佳”解决方案(除了可怕的阅读和格式设置):

.collect(Collectors.collectingAndThen(
          Collectors.groupingBy(Match::getType, Collectors.collectingAndThen(
              Collectors.toList(),
              l -> l.stream().max(Comparator.comparing(Match::getScore)).get())), Map::values))
      .forEach(m -> System.out.println(m.getType() + ": " + m.getScore()));

和:

.collect(Collectors.collectingAndThen(
          Collectors.groupingBy(Match::getType, Collectors.maxBy(Comparator.comparing(Match::getScore))), Map::values))
      .forEach(m -> m.ifPresent(ma -> System.out.println(ma.getType() + ": " + ma.getScore())));

输出(正确):

A:10
B:12
C:1

另外,我无法提取返回收集器的通用静态方法,因此我可以通过以下方式简单地在需要的地方使用它:
.collect(distinctMaxByProperty(Match::getType, Match::getScore)

任何帮助将不胜感激!


问题答案:

List当您可以首先收集最大元素时,请勿收集到中,而只是提取一个值,例如

Map<String,Match> result =
    Stream.of(new Match("A", 1), new Match("A", 2), new Match("A", 4), new Match("A", 10),
              new Match("B", 3), new Match("B", 6), new Match("B", 12), new Match("C", 1))
        .collect(Collectors.groupingBy(Match::getType, Collectors.collectingAndThen(
            Collectors.reducing(BinaryOperator.maxBy(
                                    Comparator.comparingInt(Match::getScore))),
            Optional::get)));

但是,每当您需要Optional在的上下文中提取时groupingBy,都值得检查是否具有合并功能的toMap`是否可以给出更简单的结果:

Map<String,Match> result =
    Stream.of(new Match("A", 1), new Match("A", 2), new Match("A", 4), new Match("A", 10),
              new Match("B", 3), new Match("B", 6), new Match("B", 12), new Match("C", 1))
        .collect(Collectors.toMap(Match::getType, Function.identity(),
                 BinaryOperator.maxBy(Comparator.comparingInt(Match::getScore))));

一旦有了,Map您可以通过以下方式产生所需的输出

result.values().forEach(m -> System.out.println(m.getType() + ": " + m.getScore()));

但是,如果您不需要实际的Match实例,则可以做得更简单:

Stream.of(new Match("A", 1), new Match("A", 2), new Match("A", 4), new Match("A", 10),
          new Match("B", 3), new Match("B", 6), new Match("B", 12), new Match("C", 1))
    .collect(Collectors.toMap(Match::getType, Match::getScore, Math::max))
    .forEach((type,score) -> System.out.println(type + ": " + score));


 类似资料:
  • 我想知道流(或收集器)中是否已经实现了一个功能,它首先按属性对流进行分组,然后返回列表中按另一个属性排序的第一个元素。例如,以下代码尝试使用第一个属性对对象流进行分组,然后希望收集第二个属性值最高的对象。 现在,我想用流myClassStream实现类似的功能- 我的代码使用简单的循环是: 任何帮助将不胜感激。

  • 我有一个对象流,我想找到一个最大值的一些属性,计算起来很昂贵。 作为一个特定的简单示例,假设我们有一个字符串列表,我们希望找到最酷的一个,给定函数。

  • 我有对象要按文档ID分组。分组后,我想获得它们的“最大值”。这就是我目前掌握的: 文档类: 重要的是,我已经实现了一个compareTo函数。我不确定在< code>groupingBy子句的< code>reducer参数中放什么。我也试过: 但无济于事。

  • 以我的例子为例,有一个car对象,并发现基于模型(group by)的最小和最大价格值。 但我找不到哪些汽车物品有最大和最小的价格。我怎么能那样做?

  • 问题内容: CSS 和属性可接受的最大有效值是多少? (我目前正在构建一个Web应用程序,该应用程序会创建一个非常大的可缩放容器元素,我想知道实际的限制是什么。) 问题答案: 在宽度和高度为10000000000px的元素上使用某些浏览器随附的CSS检查器:

  • 我已经设法编写了一个使用Java8Streams API的解决方案,该解决方案首先按对象路由的值对其列表进行分组,然后对每组中的对象数进行计数。它返回映射路由->long。代码如下: 和路由类: 应转换为: 请注意,映射的键数为2条路由,它是lastUpdated值最大的一条。