Check if array has duplicates

peter_budo 4 Tallied Votes 996 Views Share

Simple code to see if array of primitives has duplicates. The aim is to only check if there are any duplicates, but not to check what element is repeated, or its position etc.

PS: Do you know some handy snippet? Don't way, post it!

mKorbel commented: no idea == no solution, +8
Majestics commented: A Challenge +5
import java.util.*;

public class QuickCoding {
    public static void main(String[] args){
        int myArray[] = {0, 1, 0, 0, 2, 0, 0, 3, 0, 1};
        List<Integer> list = new ArrayList(Arrays.asList(myArray));
        Set<Integer> set = new HashSet<Integer>(list);
        if(set.size() < myArray.length){
            System.out.println("There are some duplicates");
        }
    }
}

Dani AI

Generated

The Set-size trick shown by is a clean, common approach. Two practical points worth adding given the thread: why saw a set size of 1, and what to pick for clarity vs. performance.

Arrays.asList does not expand a primitive int[] into elements — it treats the entire int[] as a single list element, which explains the size-of-1 symptom. Collections.addAll (as notes) and varargs helpers work only with object types (e.g., Integer[]), not int[]. For primitive int[] a concise, modern way to build the set without a manual loop is to use streams to box the ints and collect to a Set:

import java.util.*;
import java.util.stream.*;

int[] a = {1, 2, 3, 5, 1};
Set<Integer> s = IntStream.of(a).boxed().collect(Collectors.toSet());
if (s.size() < a.length) {
    System.out.println("duplicates found");
}

For performance: 's early-exit loop is useful when duplicates are common — it can stop far before scanning all elements. Hash-based checks give expected O(n) time and O(n) extra memory (boxing adds overhead). If memory is tight and values are in a known small non-negative range, a boolean[] or BitSet can detect duplicates without boxing (watch out for negatives and huge ranges). If performance is critical and many primitives are involved, consider primitive-collection libraries (e.g., trove/fastutil) to avoid boxing.

Muralidharan.E 14 Junior Poster in Training
import java.util.*;

public class QuickCoding {
    public static void main(String[] args){
        int myArray[] = {1, 2, 3,5,1};
        List list = new ArrayList();
 
        for(int i=0;i<myArray.length;i++)
        list.add(myArray[i]); 
 
        Set<Integer> set = new HashSet<Integer>(list);
        if(set.size() < myArray.length){
            System.out.println("There are some duplicates");
        }
    }
}
peter_budo 2,532 Code tags enforcer Team Colleague Featured Poster

sorry, but your code is just de-tour from code posted by me. As you can see from above your for loop is not need it, if you use appropriate class to convert from collection (array) to collection(integers list) loop is obsolete.

Muralidharan.E 14 Junior Poster in Training
Set<Integer> set = new HashSet<Integer>(list);

Always set size is showing as 1. so i used loop without thinking. Now i will try to workout without loop.

Thank you Peter!

JeffGrigg 170 Posting Whiz in Training

The original code snippet is quite good. Hard to "top" it.

If there a very large number of values and duplicates were expected to be common, and performance was a real concern, I might loop and exit early:

int myArray[] = {0, 1, 0, 0, 2, 0, 0, 3, 0, 1};

        Set<Integer> dups = new HashSet<Integer>();
        for (Integer value : myArray) {
        	if (dups.contains(value)) {
        		System.out.println("There are some duplicates");
        		break;
        	} else {
        		dups.add(value);
        	}
       	}

But I can't say that this code is "generally better" than the original code.

Member Avatar for Member #718641
Member #718641

You can skip the intermediate list creation, by using Collections.addAll with varargs, if the array is of an object type or just a variable number of method arguments (varargs). It does not work for arrays of primitives (like int), though:

package net.doepner;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class ArraysUtil {

    public static <T> boolean containsDuplicates(T... elements) {
        final Set<T> set = new HashSet<T>();
        Collections.addAll(set, elements);
        return set.size() < elements.length;
    }

    public static void main(String[] args) {
        final Integer[] test = { 1, 3, 5, 1 };
        System.out.println(containsDuplicates(test));
        // => true

        final String a = "foo";
        final String b = "bar";
        final String c = "bar";
        System.out.println(containsDuplicates(a, b, c));
        // => true
    }

}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.