Oscar
Oscar

Reputation: 231

Some troubles with Java ArrayList.contains()

I'm pretty new to Java and I have a problem and I can't seem to find the answer to it. I'm trying to find out if the language I pass exists in my list.

String lang = "fr, de, gb, nl, se, es";
List<String> result = new ArrayList<String>();
String[] languages = lang.split(",");
result = Arrays.asList(languages);
if (result.contains("de")) {
    return true;
} else {
    System.exit(0);
}

And this returns false, i can't understand why.

Upvotes: 0

Views: 96

Answers (7)

Safeer
Safeer

Reputation: 71

That's because array languages" contains {"fr"," de"," gb"," nl"," se"," es"} it contains " de" not "de". You can correct it in two different ways, 1: Split languages with " ," (syntax may be different). 2: compare the correct strings including space.

Upvotes: 2

Marko Topolnik
Marko Topolnik

Reputation: 200138

You are splitting on just the comma, therefore your array contains strings with spaces in front. Use this regex instead to split:

lang.split("\\s*,\\s*")

On a side note, you don't need these three lines:

List<String> result = new ArrayList<String>();
String[] languages = lang.split(...);
result = Arrays.asList(languages);

All you need is

List<String> result = Arrays.asList(lang.split(...));

Upvotes: 4

manivannan
manivannan

Reputation: 622

change your string like this

String lang = "fr,de,gb,nl,se,es";

or change like @TheLostMoind said

Upvotes: -2

Elliott Frisch
Elliott Frisch

Reputation: 201399

You get the spaces with your split, I would use split with \\s+ which will remove the white space for you.

String lang = "fr, de, gb, nl, se, es";
String[] languages = lang.split(",\\s+");
List<String> result = Arrays.asList(languages);
if (result.contains("de")) {
    System.out.println("Result contains de");
} else {
    System.out.println("Result does not contain de");
}

Output is

Result contains de

Upvotes: 1

DeiAndrei
DeiAndrei

Reputation: 947

Split the lang String after ", " or remove the spaces in the initialization

Upvotes: 0

David Limkys
David Limkys

Reputation: 5123

Your strings are separated with ", ". so if you do this:

if (result.contains(" de")

it will work.

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

"fr, de, gb, nl, se, es" 

you are checking for de instead of <space>de.

Upvotes: 0

Related Questions