【问题标题】:How to count the value of a custom data types in lists?如何计算列表中自定义数据类型的值?
【发布时间】:2017-08-17 23:43:24
【问题描述】:

我已经看到了一些关于 hashMaps 的东西,但是我们的工作还没有走到那一步。请让您的答案和有用的建议尽可能简单。

我有一个自定义数据类型,它已经被制作并且可以完美地工作,称为颜色。该类型的唯一值是 Color.BLUE、Color.RED、Color.YELLOW 和 Color.GREEN。

如果列表中的 Color.BLUE 多于其他颜色,我的任务是返回 Color.BLUE,如果列表中的 Color.RED 多于其他颜色,则返回 Color.RED,Color.GREEN 相同和 Color.YELLOW。

我已经研究并想出了这个代码:

public Color callColor(List<Card> hand) {

    int blueCards = Collections.frequency(hand, Color.BLUE);
    int redCards = Collections.frequency(hand, Color.RED);
    int greenCards = Collections.frequency(hand, Color.GREEN);
    int yellowCards = Collections.frequency(hand, Color.YELLOW);
    Color changeColorTo = Color.NONE;

    if ((blueCards > redCards) || (blueCards > greenCards) || (blueCards > yellowCards)) {
        changeColorTo = Color.BLUE;
    }

    if ((redCards > blueCards) || (redCards > greenCards) || (redCards > yellowCards)) {
        changeColorTo = Color.RED;
    }

    if ((greenCards > redCards) || (greenCards > blueCards) || (greenCards > yellowCards)) {
        changeColorTo = Color.GREEN;
    }

    if ((yellowCards > redCards) || (yellowCards > greenCards) || (yellowCards > blueCards)) {
        changeColorTo = Color.YELLOW;
    }
    return changeColorTo;
}

但是这段代码导致 blueCards、redCards、greenCards 和 YellowCards 都为 0,而它们绝对不应该为零。

因此,在这种情况下,我的 Collections 实现根本不起作用。救命!

【问题讨论】:

  • List&lt;Card&gt; hand 做得怎么样?
  • @Sanjeev 我不确定。这部分代码是为我们提供的。
  • 可以发Color类的代码吗?
  • 使用switch并自己计算频率。
  • @hattic 遍历您的列表并将卡片的颜色与您拥有的各个颜色匹配

标签: java list collections frequency


【解决方案1】:

您正在将List&lt;Card&gt; 传递给该方法,但随后您正在该列表中搜索某个Color 的频率。这就是为什么所有计数都等于 0。

【讨论】:

  • 我们收到了public Color callColor(List&lt;Card&gt; hand) {,并被告知要在下面编写代码。我应该如何编辑这个?
  • 如果你使用的是Java 8,你可以使用int blueCards = hand.stream().filter(h -&gt; Color.BLUE.equals(h.getColor())).count();等等
【解决方案2】:

您的输入列表包含卡片而不是颜色。

所以可能解决的问题是先将你的卡片列表转换为颜色列表:

hand.stream().map(Card::getColor).collect(Collectors.toList());

结果您将获得颜色列表,因此您现在可以在其上使用 Collection.frequency,而不是在初始卡片列表中。

但是,还有很多其他方法可以解决您的问题,例如使用另一个集合。

【讨论】:

    【解决方案3】:

    Collections#frequency 在给定集合中查找传递对象的出现,但在您的情况下,您希望匹配卡片集合的属性。这就是为什么每次频率计算都会为您提供0

    以下是找出每种颜色的牌数的迭代方法

    for(Card card:hand) {
    
      if(card color is equal to Color.Blue) blueCards++
      else if(card color is equal to Color.Red) redCards ++
    
      // same code for other colors
    }
    

    【讨论】:

    • 很高兴能帮到你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多