我有一个String[],其值如下:
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
给定字符串s,是否有一种测试VALUES是否包含s的好方法?
我有一个String[],其值如下:
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
给定字符串s,是否有一种测试VALUES是否包含s的好方法?
当前回答
最短解数组VALUES可能包含重复项自Java 9以来
List.of(VALUES).contains(s);
其他回答
使用Java 8,您可以创建一个流,并检查流中的任何条目是否与“s”匹配:
String[] values = {"AB","BC","CD","AE"};
boolean sInArray = Arrays.stream(values).anyMatch("s"::equals);
或作为通用方法:
public static <T> boolean arrayContains(T[] array, T value) {
return Arrays.stream(array).anyMatch(value::equals);
}
使用Array.BinarySearch(Array,obj)查找数组中的给定对象。
例子:
if (Array.BinarySearch(str, i) > -1)` → true --exists
false--不存在
您可以直接使用Arrays.asList方法以类似的方式将其初始化为List,而不是使用快速数组初始化语法,例如:
public static final List<String> STRINGS = Arrays.asList("firstString", "secondString" ...., "lastString");
然后您可以执行(如上所述):
STRINGS.contains("the string you want to find");
开发人员通常会:
Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);
上面的代码可以工作,但不需要先将列表转换为set。将列表转换为集合需要额外的时间。它可以简单到:
Arrays.asList(arr).contains(targetValue);
or
for (String s : arr) {
if (s.equals(targetValue))
return true;
}
return false;
第一个比第二个更可读。
试试看:
ArrayList<Integer> arrlist = new ArrayList<Integer>(8);
// use add() method to add elements in the list
arrlist.add(20);
arrlist.add(25);
arrlist.add(10);
arrlist.add(15);
boolean retval = arrlist.contains(10);
if (retval == true) {
System.out.println("10 is contained in the list");
}
else {
System.out.println("10 is not contained in the list");
}