Reputation: 1488
I want to compare two string arrays A, B. I want to return and/or display the elements unique to A, B and those which are in both A & B. I called my method as shown below, but I get wrong results. How to fix it ?
A = 1,2,3,4,5;
B = 1,2;
compareStringArray(A,B, true);// true means print results
Results -
--Elements in ONLY A -
3, 5
--Elements in ONLY B -
--Elements in both A & B -
2
Code-
public static ArrayList<ArrayList<String>> compareStringArray(
String[] arrayA, String[] arrayB, boolean display) {
ArrayList<ArrayList<String>> results = new ArrayList<ArrayList<String>>();
ArrayList<String> ara = new ArrayList<String>(Arrays.asList(arrayA));
ArrayList<String> arb = new ArrayList<String>(Arrays.asList(arrayB));
ArrayList<String> common = new ArrayList<String>();
for(String s : ara){
if (arb.contains(s)) {
common.add(s);
}// if
}//for
for(String s: common){
if (ara.contains(s)) {
ara.remove(s);
}// if
if (arb.contains(s)) {
arb.remove(s);
}// if
}//for
results.add(ara);
results.add(arb);
results.add(common);
if (display == true) {
ArrayList<String> als = null;
als = results.get(0);
System.out.println("\n--Elements in ONLY A - \n");
printArrayListOfStringAsCSV(als);
als = results.get(1);
System.out.println("\n--Elements in ONLY B - \n");
printArrayListOfStringAsCSV(als);
als = results.get(2);
System.out.println("\n--Elements in both A & B - \n");
printArrayListOfStringAsCSV(als);
}// if
return results;
}// compare
Upvotes: 0
Views: 314
Reputation: 533
It probebly means that the problem is in printArrayListOfStringAsCSV(). Look into it...
Upvotes: 1
Reputation: 201537
Your code is working on my machine (I had to fix main, and implement printArrayListOfStringAsCSV
so tsk-tsk) -
public static void main(String[] args) {
String[] A = { "1", "2", "3", "4", "5" };
String[] B = { "1", "2" };
compareStringArray(A, B, true);
}
public static void printArrayListOfStringAsCSV(
List<String> al) {
for (int i = 0; i < al.size(); i++) {
if (i != 0) {
System.out.print(", ");
}
System.out.print(al.get(i));
}
System.out.println();
}
And I get this output (which looks 100% to me).
--Elements in ONLY A -
3, 4, 5
--Elements in ONLY B -
--Elements in both A & B -
1, 2
Upvotes: 1