How to count the number of occurrences of an element in a List

后端 未结 22 1504
一生所求
一生所求 2020-11-22 12:25

I have an ArrayList, a Collection class of Java, as follows:

ArrayList animals = new ArrayList();
animals.add(\"bat\         


        
22条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 12:29

    Sorry there's no simple method call that can do it. All you'd need to do though is create a map and count frequency with it.

    HashMap frequencymap = new HashMap();
    foreach(String a in animals) {
      if(frequencymap.containsKey(a)) {
        frequencymap.put(a, frequencymap.get(a)+1);
      }
      else{ frequencymap.put(a, 1); }
    }
    

提交回复
热议问题