I am trying to create if condition with explicitly defined array:
So "standard" is:
public static void main(String[] args) {
int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
if(contains(number, 2)){
System.out.println("Array contain number 2");
}
}
public static boolean contains(final int[] array, final int v) {
boolean result = false;
for(int i : array){
if(i == v){
result = true;
break;
}
}
return result;
}
But how should I create something like this:
public static void main(String[] args) {
if(contains({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 2)){
System.out.println("Array contain number 2");
}
}
Because I am getting an error Array initializer is not allowed here
asked Jul 16, 2020 at 8:07
1 Answer 1
Already people have answered in comment section, But here I am showing you how you can do it in Java8, if you are looking for some fancy way like this :
boolean result = Arrays.stream(array).anyMatch(x->x==2)
or By using IntStream.
boolean result = IntStream.of(array).anyMatch(x -> x == 2)
answered Jul 16, 2020 at 8:32
lang-java
if(contains(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 2)){
contains(int v, int... array)
then you can call it like this:contains(2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)