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.
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 < strArray.length; i++){
for(int j = 0; j < i; j++){
if (strArray[i].equals(srtArray[j])){
newArray = strArray[i];
}
}
}
return newArray[];
}
}
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.
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 < 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());
}
}
}
The output is: ball apple
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:
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<String> printUnique(String[] strArray){
Set<String> set = new HashSet<String>();
Set<String> uniqueSet = new HashSet<String>();
for(int i = 0; i < strArray.length ; i++ ){
boolean b = set.add(strArray[i]);
if(b == false){
uniqueSet.add(strArray[i]);
}
}
return(uniqueSet);
}
}