Detect duplicate values in primitive Java array

前端 未结 9 1188
别跟我提以往
别跟我提以往 2020-12-18 08:21

I want to detect duplicate values in a Java array. For example:

int[] array = { 3, 3, 3, 1, 5, 8, 11, 4, 5 };

How could I get the specific

9条回答
  •  死守一世寂寞
    2020-12-18 09:08

     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");
          });
    
        }
    

提交回复
热议问题