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

后端 未结 22 1154
一生所求
一生所求 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:25
    package traversal;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Occurrance {
        static int count;
    
        public static void main(String[] args) {
            List<String> ls = new ArrayList<String>();
            ls.add("aa");
            ls.add("aa");
            ls.add("bb");
            ls.add("cc");
            ls.add("dd");
            ls.add("ee");
            ls.add("ee");
            ls.add("aa");
            ls.add("aa");
    
            for (int i = 0; i < ls.size(); i++) {
                if (ls.get(i) == "aa") {
                    count = count + 1;
                }
            }
            System.out.println(count);
        }
    }
    

    Output: 4

    0 讨论(0)
  • 2020-11-22 12:27

    What you want is a Bag - which is like a set but also counts the number of occurances. Unfortunately the java Collections framework - great as they are dont have a Bag impl. For that one must use the Apache Common Collection link text

    0 讨论(0)
  • 2020-11-22 12:28

    Alternative Java 8 solution using Streams:

    long count = animals.stream().filter(animal -> "bat".equals(animal)).count();
    
    0 讨论(0)
  • 2020-11-22 12:28
    Map<String,Integer> hm = new HashMap<String, Integer>();
    for(String i : animals) {
        Integer j = hm.get(i);
        hm.put(i,(j==null ? 1 : j+1));
    }
    for(Map.Entry<String, Integer> val : hm.entrySet()) {
        System.out.println(val.getKey()+" occurs : "+val.getValue()+" times");
    }
    
    0 讨论(0)
  • 2020-11-22 12:29

    I'm pretty sure the static frequency-method in Collections would come in handy here:

    int occurrences = Collections.frequency(animals, "bat");
    

    That's how I'd do it anyway. I'm pretty sure this is jdk 1.6 straight up.

    0 讨论(0)
  • 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<String,int> frequencymap = new HashMap<String,int>();
    foreach(String a in animals) {
      if(frequencymap.containsKey(a)) {
        frequencymap.put(a, frequencymap.get(a)+1);
      }
      else{ frequencymap.put(a, 1); }
    }
    
    0 讨论(0)
提交回复
热议问题