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

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

    List 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 set = new LinkedHashSet<>();
    set.addAll(list);
    
    for (String s : set) {
    
        System.out.println(s + " : " + Collections.frequency(list, s));
    }
    

    Method 2:

    int count = 1;
    Map map = new HashMap<>();
    Set 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);
    

提交回复
热议问题