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!");
        }
   }
}
0

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you works like a charm!
Why not use an or in the IntPredicate and have a one-liner answer? if (IntStream.of(field).anyMatch(i -> i == 1 || I == 2)) {
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!");
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.