tl;dr
For:
enum Animal { DOG , CAT }
… we can filter out matches from list of possible enum names:
List < String > names = Arrays.stream( Animal.values() ).map( Animal :: name ).toList() ;
List < String > possibleNames = List.of( "DOG" , "CAT" , "BIRD" );
List < String > invalid = new ArrayList <>( possibleNames );
invalid.removeAll( names );
When run:
names.toString() = [DOG, CAT]
possibleNames.toString() = [DOG, CAT, BIRD]
invalid.toString() = [BIRD]
Details
Your code looks good enough. But I suppose we could make the code briefer, and optimize a bit.
Let's use enum Animal { DOG , CAT }
as an example.
Keep enum names for repeated use
Get a list of the enum names, a list of strings.
Keep this list of names around if you will be doing multiple match attempts.
We sort for (a) perusing by humans, and (b) possible optimization discussed below.
List < String > names = Arrays.stream( Animal.values() ).map( Animal :: name ).sorted().toList() ;
Now search for matches.
boolean hit = names.contains( someName ) ;
boolean isInvalid = ( ! names.contains( someName ) ) ;
Optimizing for performance
If you had a very long list, and made many searches, you could optimize with a binary search. This would require the names to be in sorted order, thus our .sorted()
call in code above.
In milder situations, I would not bother with the binary search. Likely a premature optimization.
boolean hit = ( Collections.binarySearch( names , someName ) >= 0 ) ;
boolean isInvalid = ( Collections.binarySearch( names , someName ) < 0 ) ;
Multiple matches
For a list of names to be matched, use List :: removeAll
.
First, make a copy of the possible names. Then, from that copy remove the known names. Any remaining are invalid.
List < String > invalid = new ArrayList <>( possibleNames );
invalid.removeAll( names );
Apache Commons Lang
The Apache Commons Lang library offers two methods: