5

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 duplicated entry and how many times it occurs?

2
  • Which values are you looking for? The 3s or the 5s? Commented Mar 19, 2011 at 18:58
  • I am trying to find the 3s and 5s AND how any times they occur. Commented Mar 19, 2011 at 19:02

9 Answers 9

6

I'll have a Map<Integer, Integer> where the first integer is the value of the number that occurs in the array and the second integer is the count (number of occurrence).

  • Run through the array.length in a loop
  • for each item in the array, do a map.containsKey(array[i]). If there exists a number in a map, increment that number (something like map.put(array[i], map.get(array[i]) + 1). Otherwise, create a new entry in a map (e.g map.put(array[i], 1).
  • Finally, iterate through the map and retrieve all keys where value is greater than 1.
Sign up to request clarification or add additional context in comments.

1 Comment

@yannis hristofakis, nope. It was a typo. Fixed the mistake on my post.
5

Seems like a job for data structure called multiset.

Multiset<Integer> mp = HashMultiset.create();
mp.addAll(Arrays.asList(new Integer[] { 3, 3, 3, 1, 5, 8, 11, 4, 5 }));

Standard JDK 6 is primitive and do not contain multiset. If you do not want to rewrite it, you can use preexisting library like Google Guava-libraries or Apache Commons.

For example with Guava-libraries you can

    for (Integer i : mp.elementSet())
        System.out.println(i + " is contained " + mp.count(i) + " times.");

And this would output:

1 is contained 1 times.
3 is contained 3 times.
4 is contained 1 times.
5 is contained 2 times.
8 is contained 1 times.
11 is contained 1 times.

Comments

4

The answer depends on the number range in your source array. If the range is small enough you can allocate an array, loop through your source and increment at the index of your source number:

int[] counts = new int[max_value + 1];

for (int n: array) {
    counts[n]++;
}

If your source array contains an unknown or too large range, you can create a Map and count in that:

Map<Integer,Integer> counts = new HashMap<Integer,Integer>();

for (Integer n: array) {
    if (counts.containsKey(n)) {
        counts.put(n, counts.get(n) + 1);
    } else {
        counts.put(n, 1);
    }
}

NB. typed the above without the help of a JVM, getting rid of typoes is left as an exercise for the reader :-)

Comments

3
public class Duplicate {

    public static void main(String[] arg) {
        int[] array = {1, 3, 5, 6, 2, 3, 6, 4, 3, 2, 1, 6, 3};

        displayDuplicate(array);

    }

    static void displayDuplicate(int[] ar) {
        boolean[] done = new boolean[ar.length];
        for(int i = 0; i < ar.length; i++) {
            if(done[i])
                continue;
            int nb = 0;
            for(int j = i; j < ar.length; j++) {
                if(done[j])
                    continue;
                if(ar[j] == ar[i]) {
                    done[j] = true;
                    nb++;
                }
            }
            System.out.println(ar[i] + " occurs " + nb + " times");
        }
    }
}

2 Comments

Please don't answer an obvious homework question with code. Give hints or something--anything but doing his homework for him. And yeah, look at the nature of the question to determine that it's a homework question, they won't always tag it.
I just point it out since people are generally eager to help and don't really consider the nature of the question sometimes.
3
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class DuplicatedValuesInArray 
{

    public static void main(String args[]) {  
        int[] array = { 3, 3, 3, 1, 5, 8, 11, 4, 5 };
        Map<Integer, Integer> map= new HashMap<Integer, Integer>();

      for(int i=0;i<array.length;i++) {   
          if(map.containsKey(array[i]))

          map.put(array[i],map.get(array[i]) + 1);
      else
          map.put(array[i], 1);
      }

      for (Integer i : map.keySet()) {
          System.out.println(i + " is contained " + map.get(i) + " times.");
      }
   }
}

Comments

1

You can use Collectors.frecuency() and Collectors.groupingBy.

This is how i do this, hope this can help you.

    Map<Object,Long> finalValues = new HashMap<Object, Long>();

    finalValues = Arrays.asList(new Integer[] {3, 3, 3, 1, 5, 8, 11, 4, 5 })
            .stream()
            .collect(Collectors.groupingBy(e -> e, Collectors.counting()));

    //Check the output
    finalValues.entrySet().forEach(entry -> {
        System.out.println("number: " + entry.getKey() + "| Times: "+ entry.getValue());
    });

The output is:

number: 1| Times: 1
number: 3| Times: 3
number: 4| Times: 1
number: 5| Times: 2
number: 8| Times: 1
number: 11| Times: 1

You can even use frecuency to delete all the numbers that doesn't repeat:

Map finalValues = new HashMap();

    List<Integer> numbers = Arrays.asList(new Integer[]{1,2,1,3,4,4});     

    finalValues = numbers
            .stream()
            .filter(x-> Collections.frequency(numbers, x) > 1)
            .collect(Collectors.groupingBy(e -> e, Collectors.counting()));

    //Check the output
    finalValues.entrySet().forEach(entry -> {
        System.out.println("number: " + entry.getKey() + "| Times: "+ entry.getValue());
    });

The output is :

number: 1| Times: 2
number: 4| Times: 2

Comments

0

assign a counter for the first step then you can relate them to an another array assigning each number to an index then if your number is duplicated increment your counter...

Comments

0

Sort the array, then either scan it or Arrays.binarySearch + scan in either direction. Due to much fewer allocations and no wrapping, this can be faster, especially on larger arrays.

Comments

0
 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<Integer, Integer> map = new HashMap<Integer, Integer>();

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

    }

1 Comment

This answer doesn't track how many times a duplicate value occurs. Also could you add some explanation as to what the code does?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.