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

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

    There is no native method in Java to do that for you. However, you can use IterableUtils#countMatches() from Apache Commons-Collections to do it for you.

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

    So do it the old fashioned way and roll your own:

    Map<String, Integer> instances = new HashMap<String, Integer>();
    
    void add(String name) {
         Integer value = instances.get(name);
         if (value == null) {
            value = new Integer(0);
            instances.put(name, value);
         }
         instances.put(name, value++);
    }
    
    0 讨论(0)
  • 2020-11-22 12:51

    Java 8 - another method

    String searched = "bat";
    long n = IntStream.range(0, animals.size())
                .filter(i -> searched.equals(animals.get(i)))
                .count();
    
    0 讨论(0)
  • 2020-11-22 12:52
    List<String> list = Arrays.asList("as", "asda", "asd", "urff", "dfkjds", "hfad", "asd", "qadasd", "as", "asda",
            "asd", "urff", "dfkjds", "hfad", "asd", "qadasd" + "as", "asda", "asd", "urff", "dfkjds", "hfad", "asd",
            "qadasd", "as", "asda", "asd", "urff", "dfkjds", "hfad", "asd", "qadasd");
    

    Method 1:

    Set<String> set = new LinkedHashSet<>();
    set.addAll(list);
    
    for (String s : set) {
    
        System.out.println(s + " : " + Collections.frequency(list, s));
    }
    

    Method 2:

    int count = 1;
    Map<String, Integer> map = new HashMap<>();
    Set<String> set1 = new LinkedHashSet<>();
    for (String s : list) {
        if (!set1.add(s)) {
            count = map.get(s) + 1;
        }
        map.put(s, count);
        count = 1;
    
    }
    System.out.println(map);
    
    0 讨论(0)
提交回复
热议问题