2016-12-17 23 views
1

這是可能的,如果是的話,我會如何正確地做到這一點?希望能夠檢查它是否包含1和2,如果是的話繼續進行該程序。檢查一個數組,如果它包含一個整數在Java

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

回答

7

您可以在Java 8

if (IntStream.of(field).anyMatch(i -> i == 1) && 
    IntStream.of(field).anyMatch(i -> i == 2)) { 
    // has a 1 and a 2 
+0

使用IntStream謝謝你就像一個魅力! –

1

Arrays.asList作品與泛型類型,對於int[]最接近的匹配是Object。所以你得到int[]List。你可以使用Java中IntStream 8+喜歡

if (IntStream.of(field).anyMatch(x -> x == 1) && 
     IntStream.of(field).anyMatch(x -> x == 2)) { 
    System.out.println("Hello World!"); 
} 
相關問題