Reputation: 209
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
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
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
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
Reputation: 48288
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
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