如何计算列表中自定义数据类型的值?

How to count the value of a custom data types in lists?

我已经看到了一些关于 hashMap 的东西,但我们的工作还没有那么深入。请让您的回答和有用的建议尽可能简单。

我有一个自定义数据类型,它叫做 Color,它已经制作完成并且运行良好。该类型的唯一值是 Color.BLUE、Color.RED、Color.YELLOW 和 Color.GREEN.

我的任务是 return Color.BLUE 如果列表中的 Color.BLUE 比其他颜色多, return 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<Card> 传递给该方法,但您正在搜索该列表中某个 Color 的频率。这就是为什么所有计数都等于 0 的原因。

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

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

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

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

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

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
}