How to count duplicate elements in ArrayList?

前端 未结 10 1588
悲哀的现实
悲哀的现实 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条回答
  •  旧时难觅i
    2020-12-15 12:18

    Well, for that you can try to use Map

    Map countMap = new HashMap<>();
    
      for (Integer item: yourArrayList) {
    
          if (countMap.containsKey(item))
              countMap.put(item, countMap.get(item) + 1);
          else
              countMap.put(item, 1);
      }
    

    After end of forEach loop you will have a filled map with your items against it count

提交回复
热议问题