I've got an array A. I'd like to check if it contains duplicate values. How would I do so?
To check if an array contains duplicates:Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.
Simple Approach: The idea is to use nested loop and for each element check if the element is present in the array more than once or not. If present, then store it in a Hash-map.
One more way to detect duplication in the java array is adding every element of the array into HashSet which is a Set implementation. Since the add(Object obj) method of Set returns false if Set already contains an element to be added, it can be used to find out if the array contains duplicates in Java or not.
Just call uniq
on it (which returns a new array without duplicates) and see whether the uniq
ed array has less elements than the original:
if a.uniq.length == a.length puts "a does not contain duplicates" else puts "a does contain duplicates" end
Note that the objects in the array need to respond to hash
and eql?
in a meaningful for uniq
to work properly.
In order to find the duplicated elements, I use this approach (with Ruby 1.9.3):
array = [1, 2, 1, 3, 5, 4, 5, 5] => [1, 2, 1, 3, 5, 4, 5, 5] dup = array.select{|element| array.count(element) > 1 } => [1, 1, 5, 5, 5] dup.uniq => [1, 5]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With