user3505394
user3505394

Reputation: 315

Comparing string against arraylist

I have an arrayList which I need to compare against String.

What I have done:

ArrayList<String> val = new ArrayList<String>();
val= getValues();

If I print val , it gives me expected values.But

if(val.contains("abcd"))

It is returning false although at time of printing values of val it consists of abcd.

What can possibly be wrong?

Edited: How my arraylist is getting values:

IOUtils.copy(inputStream , write)
str = write.toString()

ArrayList<String> list = new ArrayList<String>();
list.addAll(Arrays.asList(str));
return list;

Upvotes: 1

Views: 134

Answers (4)

Baby
Baby

Reputation: 5092

you need to make sure that val contains string exactly as abcd(no space, no uppercase). But if it is not case-sensitive and you allow space, then you may check it like this:

boolean isExist = false;
for(int i=0;i<val.size();i++){
    if(val.get(i).trim().toLowerCase().equals("abcd")){
        isExist=true;
        break;
    }
}

Upvotes: 2

Amit  Singh
Amit Singh

Reputation: 1

contain() method works by comparing elements of Arraylist on equals() method. If your arraylist has "abcd", it should return 'true'. Try checking if your getValues() method returns some hidden character/space along with "abcd".

Upvotes: 0

anirudh
anirudh

Reputation: 4176

If getValues() returns an arraylist of strings, you need to ensure that the string "abcd" is exactly as given in parameter. Also since according to the docs, the contains method implements the equals method for comparison, you should make sure that the string has the right case as equals is case sensitive.

Upvotes: 0

maddy d
maddy d

Reputation: 1536

do something like below.

for(int i=0;i<val.size();i++){
    if(val.get(i).contains("abcd") || val.get(i).contains("ABCD")){
      // do some thing here
    }
}

Upvotes: -1

Related Questions