How to count duplicate elements in ArrayList?

前端 未结 10 1598
悲哀的现实
悲哀的现实 2020-12-15 11:55

I need to separate and count how many values in arraylist are the same and print them according to the number of occurrences.

I\'ve got an arraylist called digits :<

10条回答
  •  孤街浪徒
    2020-12-15 12:19

    You can count the number of duplicate elements in a list by adding all the elements of the list and storing it in a hashset, once that is done, all you need to know is get the difference in the size of the hashset and the list.

    ArrayList al = new ArrayList();
    al.add("Santosh");
    al.add("Saket");
    al.add("Saket");
    al.add("Shyam");
    al.add("Santosh");
    al.add("Shyam");
    al.add("Santosh");
    al.add("Santosh");
    HashSet hs = new HashSet();
    hs.addAll(al);
    int totalDuplicates =al.size() - hs.size();
    System.out.println(totalDuplicates);
    

    Let me know if this needs more clarification

提交回复
热议问题