简体   繁体   中英

How do I count the number of times an object appears in an enum?

enum Food {
      apples, oranges, grapes};
     }

Say I have the following array with items randomly place inside array from the enum above:

Food[] arr = {apples, apples, grapes, oranges, apples};

Say I want to create a method that calculates the number of times "apples" and "grapes" appears in the array, how would I go about doing this? Would I use the.equals() method for in item of enum food type? I'm lost...

Probably the easiest way to do this is with an EnumMap , an implementation of Map optimized for enum objects.

Use your enum object as the key, and an Integer for count as the value of the map: Map<Food, Integer> .

Map<Food, Integer> counts = new EnumMap<>(food.class);
for (Food f : arr) {
  counts.merge(f, 1, Integer::sum);
}

...and then you could look up the counts in the map:

int numberOfApples = counts.getOrDefault(Food.apples, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM