Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare List<String> items to String

I am getting DB values with following code:

public List<String> getPlayerNames() {
        List<String> playerNames = new ArrayList<String>();
        c = myDataBase.rawQuery("SELECT * FROM PLAYERS",null);
        while (c.moveToNext()) {

            String q = c.getString(1);
            playerNames.add(q);

        }
        c.close();
        myDataBase.close();
        return playerNames;

    }

I now want to compare the items in this List to a String value with following method:

private boolean checkIfExists(String newPlayer) {
        // TODO Auto-generated method stub

        List<String> playerNames = myDbHelper.getPlayerNames();
        //here a loop?! 

        return false;
    }

But I don't really know how to compare these list items with a string value. I tried with a for loop, but then again, a list doesn't support a .length() method to go trough all elements? Tnx!

like image 680
Matthias Vanb Avatar asked Jun 25 '26 03:06

Matthias Vanb


2 Answers

for(String playerName : playerNames){
  if(playerName.equals(newPlayer)){
    return true;
  }
}
return false;
like image 127
Alfergon Avatar answered Jun 26 '26 16:06

Alfergon


for (String playerName : playerNames) {
   if (playerName.equals(newPlayer)) {
       // do something
   }
}

you might want equalsIgnoreCase() rather than equals()

like image 45
David M Avatar answered Jun 26 '26 17:06

David M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!