我有一个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的好方法?
当前回答
开发人员通常会:
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;
第一个比第二个更可读。
其他回答
Arrays.asList(yourArray).contains(yourValue)
警告:这对基元数组无效(请参见注释)。
从java-8开始,您现在可以使用Streams。
String[] values = {"AB","BC","CD","AE"};
boolean contains = Arrays.stream(values).anyMatch("s"::equals);
要检查int、double或long数组是否包含值,请分别使用IntStream、DoubleStream或LongStream。
实例
int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 4);
可以使用Arrays类对值执行二进制搜索。如果数组未排序,则必须使用同一类中的排序函数对数组进行排序,然后对其进行搜索。
只需手动执行即可:
public static <T> boolean contains(final T[] array, final T v) {
for (final T e : array)
if (e == v || v != null && v.equals(e))
return true;
return false;
}
改进:
v!=null条件在方法中是常量。在方法调用期间,它始终计算为相同的布尔值。因此,如果输入数组很大,只计算一次这个条件会更有效,我们可以根据结果在for循环中使用简化/更快的条件。改进的contains()方法:
public static <T> boolean contains2(final T[] array, final T v) {
if (v == null) {
for (final T e : array)
if (e == null)
return true;
}
else {
for (final T e : array)
if (e == v || v.equals(e))
return true;
}
return false;
}
当我使用基本类型byte和byte[]处理低级Java时,迄今为止我得到的最好的结果是byte-Javahttps://github.com/patrickfav/bytes-java看起来是件很好的工作
值得一提的是,我进行了一次测试,比较了3个速度建议。我生成了随机整数,将它们转换为字符串并添加到数组中。然后我搜索了可能最高的数字/字符串,这对于asList().contains()来说是最坏的情况。
使用10K阵列大小时,结果是:
Sort & Search : 15
Binary Search : 0
asList.contains : 0
当使用100K阵列时,结果是:
Sort & Search : 156
Binary Search : 0
asList.contains : 32
因此,如果数组是按排序顺序创建的,那么二进制搜索是最快的,否则asList().concludes将是最好的方法。如果您有很多搜索,那么对数组进行排序可能是值得的,这样您就可以使用二进制搜索。这取决于您的应用程序。
我认为这是大多数人所期望的结果。以下是测试代码:
import java.util.*;
public class Test {
public static void main(String args[]) {
long start = 0;
int size = 100000;
String[] strings = new String[size];
Random random = new Random();
for (int i = 0; i < size; i++)
strings[i] = "" + random.nextInt(size);
start = System.currentTimeMillis();
Arrays.sort(strings);
System.out.println(Arrays.binarySearch(strings, "" + (size - 1)));
System.out.println("Sort & Search : "
+ (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
System.out.println(Arrays.binarySearch(strings, "" + (size - 1)));
System.out.println("Search : "
+ (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
System.out.println(Arrays.asList(strings).contains("" + (size - 1)));
System.out.println("Contains : "
+ (System.currentTimeMillis() - start));
}
}