我有一个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的好方法?
当前回答
如果你有谷歌收藏库,Tom的答案可以通过使用ImmutableSet简化很多(http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableSet.html)
这确实消除了初始化过程中的大量混乱
private static final Set<String> VALUES = ImmutableSet.of("AB","BC","CD","AE");
其他回答
事实上,如果按照Tom Hawtin的建议使用HashSet<String>,您就不必担心排序问题,而且您的速度与对预排序数组进行二进制搜索的速度相同,甚至可能更快。
显然,这取决于代码的设置方式,但从我的立场来看,顺序应该是:
在未排序的数组上:
哈希集as列表排序二进制(&B)
在排序数组上:
哈希集二进制的as列表
所以不管怎样,HashSet都会获胜。
值得一提的是,我进行了一次测试,比较了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));
}
}
最短解数组VALUES可能包含重复项自Java 9以来
List.of(VALUES).contains(s);
使用简单的循环是最有效的方法。
boolean useLoop(String[] arr, String targetValue) {
for(String s: arr){
if(s.equals(targetValue))
return true;
}
return false;
}
由Programcreek提供
在Java 8中,使用Streams。
List<String> myList =
Arrays.asList("a1", "a2", "b1", "c2", "c1");
myList.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);