# Search for duplicate elements in the array

**URL:** <https://www.ruby-forum.com/t/search-for-duplicate-elements-in-the-array/114646>\
**Category:** Ruby\
**Created:** [September 17, 2007, 1:23pm UTC](https://www.ruby-forum.com/t/search-for-duplicate-elements-in-the-array/114646 "2007-09-17T13:23:35Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ruhe](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/dbc845/32.png) [@Ruhe](https://www.ruby-forum.com/u/Ruhe)\
**Post date:** [September 17, 2007, 1:23pm UTC](https://www.ruby-forum.com/t/search-for-duplicate-elements-in-the-array/114646/1 "2007-09-17T13:23:35Z")

</div>

Hello.  
I have a pretty good working Java method, which sorts array of  
strings, then searches for duplicate elements. If element is  
duplicated output shows “\>\> hello \*20 times” for example.

private void printArray()

{

```
String arr[] = str.split("\\n+");

Arrays.sort(arr);

for (int j = 0; j < arr.length; j++)

{

  int count = 1;

  for (int i = j + 1; i < arr.length; i++)

  {

    if (arr[i].compareTo(arr[j]) == 0)

    {

      count++;

      j++;

    }

  }

  if (count > 1)

  {

    System.out.println(">> " + arr[j] + " *" + count + " times");

  } else

  {

    System.out.println(">> " + arr[j]);

  }

}

```

}

But the problem is that I can’t write this method in Ruby! How to make  
this in Ruby?

---

<div class="post-metadata">

**Author:** ![Ruhe](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/dbc845/32.png) [@Ruhe](https://www.ruby-forum.com/u/Ruhe)\
**Post date:** [September 17, 2007, 1:24pm UTC](https://www.ruby-forum.com/t/search-for-duplicate-elements-in-the-array/114646/2 "2007-09-17T13:24:54Z")

</div>

On 16.09.2007 13:04, Ruhe wrote:

> ```
> int count = 1;
> 
> System.out.println(">> " + arr[j] + " *" + count + " times");
> 
> ```
> 
> }
> 
> But the problem is that I can’t write this method in Ruby! How to make  
> this in Ruby?

This is way inefficient. You rather want a counter per element stored  
in a Map (HashMap or TreeMap in Java).

dups = Hash.new 0  
arr.each {|x| dups[x]+=1}  
puts dups.select {|k,v| v\>1}

You can have it on one line if you prefer:

puts arr.inject(Hash.new(0)) {|d,x| d[x]+=1; d}.select {|k,v| v\>1}

Kind regards

robert

---

<div class="post-metadata">

**Author:** ![Ruhe](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/dbc845/32.png) [@Ruhe](https://www.ruby-forum.com/u/Ruhe)\
**Post date:** [September 25, 2007, 11:05pm UTC](https://www.ruby-forum.com/t/search-for-duplicate-elements-in-the-array/114646/3 "2007-09-25T23:05:33Z")

</div>

On 16 , 15:32, Robert K. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Kind regards
> 
> ```
> robert
> 
> ```

Thanks a lot! This is a new level of programing knowledge for me.  
I’ll try to make something like this with HashMap in Java.
