How to count duplicate elements in ArrayList?

前端 未结 10 1571
悲哀的现实
悲哀的现实 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:29

    Java 8, the solution: 1. Create Map when the Key is the Value of Array and Value is counter. 
    2. Check if Map contains the Key increase counter or add a new set.
    
     private static void calculateDublicateValues(int[] array) {
          //key is value of array, value is counter
          Map map = new HashMap();
    
          for (Integer element : array) {
            if (map.containsKey(element)) {
              map.put(element, map.get(element) + 1); // increase counter if contains
            } else
              map.put(element, 1);
          }
    
          map.forEach((k, v) -> {
            if (v > 1)
              System.out.println("The element " + k + " duplicated " + v + " times");
          });
    
        }
    

提交回复
热议问题