You could simply use ArrayUtils.contains from Apache Commons Lang library.
public boolean contains(final int[] array, final int key) {
return ArrayUtils.contains(array, key);
}
Answer from Reimeus on Stack OverflowYou could simply use ArrayUtils.contains from Apache Commons Lang library.
public boolean contains(final int[] array, final int key) {
return ArrayUtils.contains(array, key);
}
Here is Java 8 solution
public static boolean contains(final int[] arr, final int key) {
return Arrays.stream(arr).anyMatch(i -> i == key);
}
Arrays.asList(yourArray).contains(yourValue)
Warning: this doesn't work for arrays of primitives (see the comments).
Since java-8 you can now use Streams.
String[] values = {"AB","BC","CD","AE"};
boolean contains = Arrays.stream(values).anyMatch("s"::equals);
To check whether an array of int, double or long contains a value use IntStream, DoubleStream or LongStream respectively.
Example
int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 4);
Concise update for Java SE 9
Reference arrays are bad. For this case we are after a set. Since Java SE 9 we have Set.of.
private static final Set<String> VALUES = Set.of(
"AB","BC","CD","AE"
);
"Given String s, is there a good way of testing whether VALUES contains s?"
VALUES.contains(s)
O(1).
The right type, immutable, O(1) and concise. Beautiful.*
Original answer details
Just to clear the code up to start with. We have (corrected):
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
This is a mutable static which FindBugs will tell you is very naughty. Do not modify statics and do not allow other code to do so also. At an absolute minimum, the field should be private:
private static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
(Note, you can actually drop the new String[]; bit.)
Reference arrays are still bad and we want a set:
private static final Set<String> VALUES = new HashSet<String>(Arrays.asList(
new String[] {"AB","BC","CD","AE"}
));
(Paranoid people, such as myself, may feel more at ease if this was wrapped in Collections.unmodifiableSet - it could then even be made public.)
(*To be a little more on brand, the collections API is predictably still missing immutable collection types and the syntax is still far too verbose, for my tastes.)
Arrays.asList(perm).contains(num)
from How can I test if an array contains a certain value?
for (int i = 0; i < perm.length; i++)
this is not enough to loop like this, if collision happens some slots would have been not initalized.
Overall, for this task you better initialize array with values in order and then shuffle it by using random permutation indexes
here is a complete answer
int[] array = {3,9, 6, 5, 5, 5, 9, 10, 6, 9,9};
SortedSet<Integer> s = new TreeSet();
int numberToCheck=61;
for (int i = 0; i < array.length; i++) {
s.add(array[i]);
}
System.out.println("Number contains:"+!(s.add(numberToCheck)));
System.out.println("Sorted list:");
System.out.print(s);