Sheriff Said Elahl Sheriff Said Elahl - 6 months ago 12
Java Question

checking the existence of string in Arraylist

I've a code that check the existence of arraylist elements in another arraylist , if found it add this element to a new arraylist. (kind of filtering).

ArrayLists Names:

checking elements arraylist: CoreSite.
Reference ArrayList: SpinnerSelectionArrayList. (received from multichoice spinner)
New ArrayList: MCoreSite.


the problem is all the possible ways I tried only compare the element to first element of the reference list! if match it counts. if not, it doesn't check with the second element of the reference arraylist .. and I can't find wwhy?!

I used contains(), and I also try to count and check the result of count.

Edit: Solved, the spinner result was returning extra space after every comma, that is why only the first element is matching :) .. many thanks

the code:

ReaderGo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SpinnerSelectionString = multiSpinner.getSpinnerText();
if(SpinnerSelectionString == null){
Toast.makeText(getApplicationContext(), "Select Core Sites First", Toast.LENGTH_LONG).show();
}
else {
SpinnerSelectionString = SpinnerSelectionString.replaceAll(",", "\",\"");
SpinnerSelectionString = "[\"" + SpinnerSelectionString + "\"]";


try {
JSONArray jsonArray = new JSONArray(SpinnerSelectionString);
SpinnerSelectionStringArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
SpinnerSelectionStringArray[i] = jsonArray.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
}

Collections.addAll(SpinnerSelectionArrayList, SpinnerSelectionStringArray);

MCoreSite.clear();

for (int i = 0; i < CoreSite.size(); i = i + 1) {
int count = Collections.frequency(SpinnerSelectionArrayList, CoreSite.get(i));
if (count!=0) {
MCoreSite.add(CoreSite.get(i));
}
}
Toast.makeText(getApplicationContext(), SpinnerSelectionArrayList.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), CoreSite.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), MCoreSite.toString(), Toast.LENGTH_LONG).show();

}
}

});


the below are the toast screenshots for the three arrays:

The Elements Array:

enter image description here

The Referrence Array:
enter image description here

The Result list:
enter image description here

Answer

Try the below code:

ArrayList<String> result = new ArrayList();
for(int i = 0; i < firstList.size(); i++) {
    String item = firstList.get(i);
    if(secondList.contains(item)) {
        result.add(item);
    }
}

Result is the list of elements that exist in the first List AND the second. If I understand correctly, this is what you wanted.

Educational fact - this will work because lists use equals() to check whether two elements are the same, not ==. Therefore, two different Strings with the same contents will be considered a common element :-)