简体   繁体   中英

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?

Try this code snippet:

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

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

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");

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");

你需要split()字符串

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM