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

后端 未结 22 1509
一生所求
一生所求 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:28

    Map hm = new HashMap();
    for(String i : animals) {
        Integer j = hm.get(i);
        hm.put(i,(j==null ? 1 : j+1));
    }
    for(Map.Entry val : hm.entrySet()) {
        System.out.println(val.getKey()+" occurs : "+val.getValue()+" times");
    }
    

提交回复
热议问题