How do I determine whether an array contains a particular value in Java?

后端 未结 29 3704
予麋鹿
予麋鹿 2020-11-21 05:00

I have a String[] with values like so:

public static final String[] VALUES = new String[] {\"AB\",\"BC\",\"CD\",\"AE\"};

Given

29条回答
  •  佛祖请我去吃肉
    2020-11-21 05:38

    Arrays.asList(yourArray).contains(yourValue)
    

    Warning: this doesn't work for arrays of primitives (see the comments).


    Since java-8 you can now use Streams.

    String[] values = {"AB","BC","CD","AE"};
    boolean contains = Arrays.stream(values).anyMatch("s"::equals);
    

    To check whether an array of int, double or long contains a value use IntStream, DoubleStream or LongStream respectively.

    Example

    int[] a = {1,2,3,4};
    boolean contains = IntStream.of(a).anyMatch(x -> x == 4);
    

提交回复
热议问题