Note that there are some explanatory texts on larger screens.

plurals
  1. POfind duplicate words in java array and return array with unique duplicate words - use method
    primarykey
    data
    text
    <p>I am new to java, and am confused with the problem. This is what I came up so far. I am still working on it, if I come up with any progress, I'll post it here.</p> <pre><code>public class charArray { public static void main(String[] args) { String[] strArray = new String[] {"apple", "ball", "cat", "apple", "ball", "apple"}; //output should be ["apple", "ball"] checkDuplicate(strArray); } public static String[] checkDuplicate(String[] strArray){ String[] newArray = new String[]{}; for(int i = 0; i &lt; strArray.length; i++){ for(int j = 0; j &lt; i; j++){ if (strArray[i].equals(srtArray[j])){ newArray = strArray[i]; } } } return newArray[]; } </code></pre> <p>}</p> <hr> <p>New progress: Ok, my mediocre head has gone this far: (and the solution works) It prints out the unique array of Duplicate elements. But now I need to implement the same code, by calling a method. Any help is appreciated.</p> <pre><code>import java.util.*; public class setChar { public static void main(String[] args) { String[] strArray = new String[] {"apple", "ball", "cat", "apple", "ball", "apple"}; Set set = new HashSet(); Set uniqueSet = new HashSet(); for(int i = 0; i &lt; strArray.length ; i++ ){ boolean b = set.add(strArray[i]); if(b == false){ uniqueSet.add(strArray[i]); } } Iterator it = uniqueSet.iterator(); while (it.hasNext()){ System.out.println(it.next()); } } } </code></pre> <p>The output is: <strong>ball apple</strong></p> <hr> <p>Finally implemented with method, with proper return type. Please let me know, if this can be further optimized. Thank all for you suggestions. Here is the working code:</p> <pre><code>public class retUnique { public static void main(String[] args) { String[] strArray = new String[] {"apple", "ball", "cat", "apple", "ball", "apple"}; System.out.println(printUnique(strArray)); } public static Set&lt;String&gt; printUnique(String[] strArray){ Set&lt;String&gt; set = new HashSet&lt;String&gt;(); Set&lt;String&gt; uniqueSet = new HashSet&lt;String&gt;(); for(int i = 0; i &lt; strArray.length ; i++ ){ boolean b = set.add(strArray[i]); if(b == false){ uniqueSet.add(strArray[i]); } } return(uniqueSet); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload