Java 查找数组中是否存在字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3571945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find if a String is present in an array
提问by test
OK let's say I have an array filled with {"tube", "are", "fun"} and then I have a JTextField and if I type either one of those commands to do something and if NOT to get like a message saying "Command not found".
好吧,假设我有一个填充了 {"tube", "are", "fun"} 的数组,然后我有一个 JTextField,如果我输入这些命令中的任何一个来做某事,如果没有得到像一条消息“找不到相关命令”。
I tried looking in Java docs but all I am getting is things that I don't want like questions and stuff... so, how is this done? I know there is a "in array" function but I'm not too good with combining the two together.
我尝试查看 Java 文档,但我得到的只是我不想要的问题之类的东西……那么,这是如何完成的?我知道有一个“数组中”函数,但我不太擅长将两者结合在一起。
Thanks.
谢谢。
Here is what I have so far:
这是我到目前为止所拥有的:
String[] dan = {"Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue"};
boolean contains = dan.contains(say.getText());
but I am getting cannot find symbol in dan.contains
但我在 dan.contains 中找不到符号
采纳答案by Pablo Fernandez
This is what you're looking for:
这就是你要找的:
List<String> dan = Arrays.asList("Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue");
boolean contains = dan.contains(say.getText());
If you have a list of not repeatedvalues, prefer using a Set<String>
which has the same containsmethod
如果您有一个不重复值的列表,最好使用Set<String>
具有相同contains方法的 a
回答by Jim Garrison
If you can organize the values in the array in sorted order, then you can use Arrays.binarySearch()
. Otherwise you'll have to write a loop and to a linear search. If you plan to have a large (more than a few dozen) strings in the array, consider using a Set instead.
如果您可以按排序顺序组织数组中的值,则可以使用Arrays.binarySearch()
. 否则,您将不得不编写一个循环和线性搜索。如果您计划在数组中有一个大的(超过几十个)字符串,请考虑使用 Set 代替。
回答by u290629
String[] a= {"tube", "are", "fun"};
Arrays.asList(a).contains("any");
回答by John Kugelman
Use Arrays.asList()
to wrap the array in a List<String>
, which does have a contains()
method:
使用Arrays.asList()
包裹在一个阵列List<String>
,它确实有一个contains()
方法:
Arrays.asList(dan).contains(say.getText())
回答by Dream Lane
This can be done in java 8 using Stream.
这可以使用 Stream 在 java 8 中完成。
import java.util.stream.Stream;
String[] stringList = {"Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue"};
boolean contains = Stream.of(stringList).anyMatch(x -> x.equals(say.getText());