Instead of null check, you can use Stream.ofNullable() (available from Java 9 onwards) which will create a stream with a single element (list of processors) or empty stream. Apply flatMap() to turn it to a stream of strings. And then apply anyMatch() as a terminal operation which will determine whether at least one process in the stream matches with the given predicate.
Note: that condition !Arrays.stream().anyMatch() means that none of elements in the stream should match the predicate passed to the anyMatch(). And that is the meaning of the operation noneMath(). A change of the terminal operation will make the condition more readable by eliminating the need in logical not in front of it Arrays.stream().noneMath().
Another improvement that is made to this code was inspired by suggestions from Holger and k314159.
Stream of enum constants Arrays.stream(MyEnumCode.values())... from the original code that is used in the condition discussed above has a performance overhead. Method values() creates an array of enum constants at every call. And it will be invoked for every element in the list. Therefore it makes sense to introduce a local variable that will store a Set of enum-names and check every element in the stream against this set.
Also as Holger pointed out null-friendly solution will disguise the problem. anyMatch() will return false in case of an empty stream and this result will be accepted as valid instead of raising NPE, and then this list can be stored somewhere and will cause problems in the future.
Since I'm providing two solutions here I've implemented one in such a way that it will raise an exception with a custom message, and another as being null-friendly by using Stream.ofNullable().
public static boolean containsNonEnumCode(List<String> processCodes) {
Set<String> names = getEnumNames(MyEnumCode.class);
return Stream.ofNullable(processCodes)
.flatMap(List::stream)
.anyMatch(process -> !names.contains(process));
}
Solution for Java 8 (requested by PO in the comment) implemented as null-hostile by using Objects.requireNonNull().
public static boolean containsNonEnumCode(List<String> processCodes) {
Set<String> names = getEnumNames(MyEnumCode.class);
return Objects.requireNonNull(processCodes, "processCodes list in null")
.stream()
.anyMatch(process -> !names.contains(process));
}
The method below expects the Class of an enum as a parameter and generates a Set of enum names.
public static <T extends Enum<T>> Set<String> getEnumNames(Class<T> enumClass) {
return EnumSet.allOf(enumClass).stream()
.map(T::name)
.collect(Collectors.toSet());
}