How to Check if an Array Contains a Value in Java Efficiently?
03 Jun 20141. Four Different Ways to Check If an Array Contains a Value
1.Using List:
public static boolean useList(String[] arr, String targetValue) {
return Arrays.asList(arr).contains(targetValue);
}
2.Using Set:
public static boolean useSet(String[] arr, String targetValue) {
Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);
}
3.Using a simple loop:
public static boolean useLoop(String[] arr, String targetValue) {
for(String s: arr){
if(s.equals(targetValue))
return true;
}
return false;
}
4.Using Arrays.binarySearch(): The code below is wrong, it is listed here for completeness. binarySearch() can ONLY be used on sorted arrays. You will the result is weird below.
public static boolean useArraysBinarySearch(String[] arr, String targetValue) {
int a = Arrays.binarySearch(arr, targetValue);
if(a > 0)
return true;
else
return false;
}