0

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
2
  • 8
    if(contains(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 2)){ Commented Jul 16, 2020 at 8:09
  • 2
    You could change the signature of contains to this: contains(int v, int... array) then you can call it like this: contains(2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) Commented Jul 16, 2020 at 8:13

1 Answer 1

2

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
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.