Find the unique array element/s...
package abc;
import java.util.ArrayList;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
// { 6, 1, 9, 2, 5, 6, 7, 4, 8, 3, 7, 5, 4, 2, 1 } //Find unique element in the array
int[] num = { 6, 1, 9, 2, 5, 6, 7, 4, 8, 3, 7, 5, 4, 2, 1 };
int numLength = num.length;
ArrayList<Integer> alist = new ArrayList<>();
for (int i = 0; i < numLength; i++) {
alist.add(num[i]);
}
ArrayList<Integer> alist1 = new ArrayList<>();// ArrayList of duplicate numbers
System.out.println(Arrays.asList(num));// [[I@53bd815b]
System.out.println(Arrays.toString(num));// [6, 1, 9, 2, 5, 6, 7, 4, 8, 3, 7, 5, 4, 2, 1]
for (int i = 0; i < numLength; i++) {
for (int j = 0; j < numLength; j++) {
if (!(i == j)) {
if ((num[i] == num[j])) {
int x = num[i];
int y = num[j];
alist1.add(x);
//alist1.add(y); no need of this, but having this there is no harm
}
}
}
}
System.out.println("alist=" + alist);// [6, 1, 9, 2, 5, 6, 7, 4, 8, 3, 7, 5, 4, 2, 1]
System.out.println("alist1=" + alist1);// [6, 1, 2, 5, 6, 7, 4, 7, 5, 4, 2, 1]
alist.removeAll(alist1);
System.out.println("alist-the unique elements = " + alist);// [9, 8, 3]
}
}
Output:
[[I@4361bd48]
[6, 1, 9, 2, 5, 6, 7, 4, 8, 3, 7, 5, 4, 2, 1]
alist=[6, 1, 9, 2, 5, 6, 7, 4, 8, 3, 7, 5, 4, 2, 1]
alist1=[6, 1, 2, 5, 6, 7, 4, 7, 5, 4, 2, 1]
alist-the unique elements = [9, 8, 3]
No comments:
Post a Comment