Teddu
Teddu

Reputation: 209

contains() method is not working for Arrays.asList in java

I have a string object that looks like:

String color = "black, pink, blue, yellow";

Now I want to convert it into an array and find a color. Something like this:

boolean check = Arrays.asList(color).contains("pink");

Which always gives false.

Can anyone help me with this?

Upvotes: 4

Views: 3677

Answers (6)

Aleksandr Podkutin
Aleksandr Podkutin

Reputation: 2580

Your string variable color is not an array, so first of all you need to create array from that string variable with split(String dilemeter) method and create ArrayList from splitted string, like this:

List<String> arrList = Arrays.asList(color.split(", "));

After that you can check if arrList contains some element:

boolean check = arrList.contains("pink");

Upvotes: 3

Nicolas Filotto
Nicolas Filotto

Reputation: 44995

Your problem is related to the fact that color is a String not an array so Arrays.asList(color) will create a List which contains only one element that is "black, pink, blue, yellow" that is why it returns false.

You need first to convert it as an array using split(String regex) as next:

// Here the separator used is a comma followed by a whitespace character
boolean check = Arrays.asList(color.split(",\\s")).contains("pink")

If you only want to know if color contains "pink", you can also consider using String#contains(CharSequence s)

boolean check = color.contains("pink");

Upvotes: 3

Abhishek
Abhishek

Reputation: 2525

Your color variable is a string. When you convert to a list it will be inserted as a single string. you can check the output of the following

Arrays.asList(color).size()

The above will always return 1, stating that your understanding that a string with comma's won't be automagically split and converted into a list.

you can split at every ' followed by a space as shown below to get your expected output.

System.out.println(Arrays.asList(color.split(", ")).contains("pink"));

The space is important in the split because your string contains spaces.

Upvotes: 1

split colors to "," , turn that into an arraylist and check if a string is present:

    String color = "black, pink, blue, yellow";
    boolean isThere = Arrays.asList(color.split(",")).contains("black");

    System.out.println("is black present: " + isThere);

Upvotes: 1

Arthur Eirich
Arthur Eirich

Reputation: 3638

Try this code snippet:

boolean check = Arrays.asList("black", "pink", "blue", "yellow").contains("pink");

I wouldn't recommend using String to store multiple values.

Upvotes: 3

AutomatedMike
AutomatedMike

Reputation: 1512

you need to split() the string

Upvotes: 2

Related Questions