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

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

    Simple Way to find the occurrence of string value in an array using Java 8 features.

    public void checkDuplicateOccurance() {
            List duplicateList = new ArrayList();
            duplicateList.add("Cat");
            duplicateList.add("Dog");
            duplicateList.add("Cat");
            duplicateList.add("cow");
            duplicateList.add("Cow");
            duplicateList.add("Goat");          
            Map couterMap = duplicateList.stream().collect(Collectors.groupingBy(e -> e.toString(),Collectors.counting()));
            System.out.println(couterMap);
        }
    

    Output : {Cat=2, Goat=1, Cow=1, cow=1, Dog=1}

    You can notice "Cow" and cow are not considered as same string, in case you required it under same count, use .toLowerCase(). Please find the snippet below for the same.

    Map couterMap = duplicateList.stream().collect(Collectors.groupingBy(e -> e.toString().toLowerCase(),Collectors.counting()));
    

    Output : {cat=2, cow=2, goat=1, dog=1}

提交回复
热议问题