开发者社区> 问答> 正文

该代码段正在编译吗?

上周末我在阅读有关Java 14预览功能记录的一些内容时,我不想提这个问题,因为这似乎是Brian Goetz的代码,我们都知道这个人是谁以及Java生态系统的代表是什么,但这已经开始了从那时起,我就知道了,我知道它将为我学习。

链接在这里。https://www.infoq.com/articles/java-14-feature-spotlight/?utm_campaign=infoq_content&utm_source=infoq&utm_medium=feed&utm_term=Java

是这样的。

record PlayerScore(Player player, Score score) {
    // convenience constructor for use by Stream::map
    PlayerScore(Player player) { this(player, getScore(player)); }
}

List<Player> topN
    = players.stream()
             .map(PlayerScore::new)
             .sorted(Comparator.comparingInt(PlayerScore::score))
             .limit(N)
             .map(PlayerScore::player)
             .collect(toList());

我认为这一行正在返回分数参考。

getScore(player)

也许您在我了解它要做什么之前就已经看到了它,但是有些东西我却不明白。也许我错了。

这条线

.sorted(Comparator.comparingInt(PlayerScore::score))

API comparingInt是这样的。

public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) {

但是只要我了解方法参考

PlayerScore::score

从记录元组返回分数参考对吗?不是整数或导致整数

否则这会使代码编译,我认为这可能是输入错误。

record PlayerScore(Player player, int score) {
    // convenience constructor for use by Stream::map
    PlayerScore(Player player) { this(player, getScore(player)); }
}

根据我的理解,此代码无法像我之前所说的那样编译,可能是错误的。

问题来源:Stack Overflow

展开
收起
montos 2020-03-21 22:03:44 1086 0
1 条回答
写回答
取消 提交回答
  • 之所以不能编译的原因可能是因为Score是类型而不是Integer值。你会需要比较做Score的record PlayerScore是确保两件事情;

    1. 使用Comparator.comparing时:
      List<Player> topN  = players.stream()
       .map(PlayerScore::new)
       .sorted(Comparator.comparing(PlayerScore::score)) //here
       .limit(N)
       .map(PlayerScore::player)
       .collect(toList());
      
    2. 确保分数工具Comparable如:
      class Score implements Comparable<Score> {
      @Override
      public int compareTo(Score o) {
          return 0; // implementation
      }
      

    } 可悲的是,我`Score`在链接文档中也看不到您的类的实现,这对于了解作者(或编辑者)在此处到底错过了什么至关重要。例如,简单的`record`定义更改将使现有代码起作用: record PlayerScore(Player player, Integer score) { // convenience constructor for use by Stream::map PlayerScore(Player player) { this(player, getScore(player)); } }

    List topN = players.stream() .map(PlayerScore::new) .sorted(Comparator.comparingInt(PlayerScore::score)) .limit(N) .map(PlayerScore::player) .collect(Collectors.toList()); ``` 只需看一下该部分,因为它与前面的示例是连续的,因此相关的重要因素是的返回类型 getScore(Player player)

    // notice the signature change
    static int getScore(Player player) {
        return 0;
    }
    

    回答来源:Stack Overflow

    2020-03-21 22:06:22
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
15分钟打造你自己的小程序 立即下载
小程序 大世界 立即下载
《15分钟打造你自己的小程序》 立即下载