Check if String in String[] is in ArrayList<string>

22,251

Solution 1

If you have a String myString and an ArrayList<String> myListOfStrings, you can check if myString is in the list like this:

myListOfStrings.contains( myString );

This will return a boolean (true/false) - true if the strings was found, false if not.

In your case you would want to run through the array of strings and match each of them to the SmileyList like this:

for( String s : splitted ) {
   if( SmileyList.contains( s ) ) {
     //Do what you need to do if the string is in the SmileyList.
   }
}

Solution 2

String array[] = ... ; 
List<String> list = ... ;
// check if anything in array is in list
for(String str : array)
    if(list.contains(str)) doSomething() ;

If you want do something for every match, the code above will work. If you only want to do something once if there was a match (and not for every match), you will need to add a break statement in the if sentence.

Solution 3

You can iterate over the array (e.g. with a for loop over splitted.length), querying your list with myList.contains(splitted[i]). The query will return a boolean.

If you need to check if all items in the array are present in the List, there is a comfortable alternative with myList.containsAll(Arrays.asList(splitted))

There is another concise alternative without looping to check if any item of the array is present in the list :

List splitList = Arrays.asList(splitted);
splitList.retainAll(myList);

splitList.isEmpty() will then return false, if any item of the lists is matching.

The contents of the splitList will show all strings that have matched.

Solution 4

Depending on how large your array and ArrayList are and how many times you will access them, you might want to use a HashSet instead of an ArrayList so that you can get a fast look up with the hashed contains() method instead of having to iterate through the ArrayList. Something like this:

boolean containsString(ArrayList<String> stringArrayList, String[] stringArray) {
    Set<String> stringSet = new HashSet<String>(stringArrayList); // if same input is used reused, might want this outside the method

    for (String s : stringArray) {
        if (stringSet.contains(s)) {
            return true;
        }
    }

    return false;
}
Share:
22,251
safari
Author by

safari

Welcome on my Profile I'm 20 years old, probably not a bad Android programmer and now just started with IOS.

Updated on February 25, 2020

Comments

  • safari
    safari about 4 years

    I just built a Broadcast Receiver with which I can get the incoming text messages, than I split the text message when there's a space and save it into a String[].

    Now I need to check if in this String[] is something from my database. For that I created a ArrayList<String>, which gets all the entries from the corresponding column. Now I need to check if a String in my ArrayList is the same in my String[] from the text message, but I don't know how to realize that.

    Is there an easy and fast way to check that, also I need to know which String is in both of them?

    SmileySmsReceiver:

      package de.retowaelchli.filterit.services;
    
    
        import java.util.ArrayList;
    
        import de.retowaelchli.filterit.database.SFilterDBAdapter;
        import android.content.BroadcastReceiver;
        import android.content.Context;
        import android.content.Intent;
        import android.database.Cursor;
        import android.os.Bundle;
        import android.telephony.SmsMessage;
        import android.util.Log;
        import android.widget.Toast;
    
    
    
        public class SmileySmsReceiver extends BroadcastReceiver {
    
            @Override
            public void onReceive(Context context, Intent intent) 
            {
                //Datenbank definieren
                SFilterDBAdapter mDbHelper = new SFilterDBAdapter(context);
    
    
                //---get the SMS message passed in---
                Log.d("SmileySmsReceiver", "Yes it calls the onReceive");
                Bundle bundle = intent.getExtras();        
                SmsMessage[] msgs = null;
                String str = "";            
                if (bundle != null)
                {
                    Log.d("SmileySmsReceiver", "Bundle is not null");
                    //---retrieve the SMS message received---
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    msgs = new SmsMessage[pdus.length];            
                    for (int i=0; i<msgs.length; i++){
                        msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
                        str += "SMS from " + msgs[i].getOriginatingAddress();                     
                        str += " :";
                        str += msgs[i].getMessageBody().toString();
                        str += "\n";        
                    Log.d("SmileySmsReceiver","Was steht in der Nachricht?: " + str);
    
                    String[] splited = str.split("\\s+");
    
                    //Hier werden die Strings der Smileys aus der Datenbank gezogen
                    mDbHelper.open();
                    Cursor c = mDbHelper.getAllSFilter();
    
                    ArrayList<String> SmileyList = new ArrayList<String>();
                    c.getColumnIndex(SFilterDBAdapter.KEYWORD);
                    int ColumnIndex = c.getColumnIndex(SFilterDBAdapter.KEYWORD);
                        if(c!=null)
                            {
                            //Hier werden die Smileys in die ArrayList geschrieben
                            while(c.moveToNext()){
                                String infoItem = c.getString( ColumnIndex );
                                SmileyList.add(infoItem);
                            }
    <------------------------- FROM HERE ON I NEED YOUR GUYS HELP ------------------------------->
                    }
                    }
                    //---display the new SMS message---
                    Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
                }                         
            }
        }
    
  • Xavi López
    Xavi López over 12 years
    It might be positive to add an exit condition to the loop for efficiency. The OP only wants to know if at least one element is contained in the list.
  • kostja
    kostja over 12 years
    definitely, it would be positive to break the loop once you have the answer - I simply considered control flow outside the scope of the question
  • safari
    safari over 12 years
    thx for you awnser, but how I find out now, which String was in both of them?
  • kaspermoerch
    kaspermoerch over 12 years
    If if( SmileyList.contains( s ) ) returns true, the string that was in both is equal to s.
  • kaspermoerch
    kaspermoerch over 12 years
    I'm not quite sure I understand your question. Do you need the index/position of s in the original String? Do you need the value of s? Do you need the index of s in splitted?
  • safari
    safari over 12 years
    the value of s, do i need, i think. I need to know what String is in the ArrayList and the String[]... got it?
  • kaspermoerch
    kaspermoerch over 12 years
    Okay - I'll try to explain more in depth. We run through the strings in the array splitted one by one, creating a reference s to the one we're currently working with. We then "ask" the ArrayList SmileyList if it contains a string that is equal to s. If it does we know that s which we got form splitted (this means it is in splitted) is also in SmileyList meaning it is in both. The String which is in both the ArrayList and the String[] is s. We then do what needs to be done in this situation.