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

advertisements

I've seen something about hashMaps, but we haven't gotten that far in our work. Please keep your answers and helpful suggestions as simple as you can manage.

I have a custom data type that is already made and works perfectly called Color. The only values of the type are Color.BLUE, Color.RED, Color.YELLOW, and Color.GREEN.

My task is to return Color.BLUE if there are more Color.BLUE in the list than the other colors, to return Color.RED if there are more Color.RED in the list than other colors, same for Color.GREEN and Color.YELLOW.

I have researched and and came up with this code:

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;
}

but this code causes blueCards, redCards, greenCards, and yellowCards all to be 0 when they should definitely not be zero.

So, in this case, my Collections implementation did not work at all. Help!


You are passing a List<Card> to the method, but then you're searching for the frequency of a certain Color in that list. That's why all counts are equal to 0.