1

Is this possible and if so how would I do this correctly? Want to be able to check if it contains 1 and 2 and if so go on with the program.

import java.util.*;

public class test
{
    public static void main(String [] args) {
        int[] field = {1, 2};

        if (Arrays.asList(field).contains(1) && Arrays.asList(field).contains(2)) {
            System.out.println("Hello World!");
        }
   }
}

2 Answers2

8

You can use IntStream in Java 8

if (IntStream.of(field).anyMatch(i -> i == 1) &&
    IntStream.of(field).anyMatch(i -> i == 2)) {
    // has a 1 and a 2
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

Arrays.asList works with generic types, the closest match for an int[] is Object. So you get a List of int[]. You could use IntStream in Java 8+ like

if (IntStream.of(field).anyMatch(x -> x == 1) && 
        IntStream.of(field).anyMatch(x -> x == 2)) {
    System.out.println("Hello World!");
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249