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

不问归期 提交于 2019-12-23 18:23:23

问题


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?


回答1:


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



回答2:


Try this code snippet:

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

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




回答3:


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



回答4:


you need to split() the string




回答5:


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



回答6:


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.



来源:https://stackoverflow.com/questions/40717271/contains-method-is-not-working-for-arrays-aslist-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!