This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Question: How do I determine if an array contains a specific value in Java?

I have a String[] that looks like this:

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

Given String s, is there a good way to test if VALUES contain s?

Answer:


A lot of knowledge points, really need to write out will master ! ! !   \color{purple} a lot of knowledge points, really need to write out just can master!! {~}


Arrays.asList(yourArray).contains(yourValue)
Copy the code

Warning: This does not apply to graph tuples (see comments). Since Java-8 you can now use streams.

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

To check whether the array 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);Copy the code

Answer:

A brief update to Java SE 9

It is an error to reference an array. In this case, we have to play catch-up. Starting with Java SE 9, we have set.of.

private static final Set<String> VALUES = Set.of(
    "AB","BC","CD","AE"
);
Copy the code

“Given String, is there a good way to test if VALUES contains s?”

VALUES.contains(s)

Order 1.

The right types, immutable, O (1) and concise. The beautiful. * Original answer details

Just to clean up the code. We (corrected) :

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

This is a mutable static function, which FindBugs will tell you is naughty. Don’t modify static variables, and don’t let other code do the same. Absolute minimum value, the field should be private:

private static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
Copy the code

(Note that you can actually delete the new String[]; A).

Reference arrays are still bad, we need a collection:

private static final Set<String> VALUES = new HashSet<String>(Arrays.asList(
     new String[] {"AB","BC","CD","AE"}
));
Copy the code

(such as my own paranoia, if it is wrapped, may feel more comfortable Collections. UnmodifiableSet – even it can be open.)

(* For further branding, the Collections API still lacks an immutable collection type, and the syntax is still too verbose for my taste.)

The article translated from am2dgbqfb6mk75jcyanzabc67y ac4c6men2g7xr2a – stackoverflow – com. Translate. Goog/questions / 1…

Author’s advice: Learn flow anyMatch!!

Thank you for reading this, if this article is well written and if you feel there is something to it

Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!

If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️