How to know which element matched in java-8 anymatch?
Use a filter
operation for the conditions and findFirst
to get the first match, then transform to the respective Country.China
or Country.USA
otherwise return Country.Others
if there was not match.
return list.stream()
.filter(str -> "China".equals(str) || "USA".equals(str))
.findFirst()
.map(s -> "China".equals(s) ? Country.China : Country.USA)
.orElse(Country.Others);
Alternatively:
return Stream.of(Country.values()) // or Arrays.stream(Country.values())
.filter(o -> list.contains(o.toString()))
.findFirst().orElse(Country.Others);
The first solution will always check for "China" before checking for "USA" which is the exact equivalent of your imperative approach, However, the latter doesn't always respect that order, rather it depends on the order of the enum constants declarations in Country
.
If the string matches the enum token then it's pretty simple:
return Arrays.stream(Country.values())
.filter(c -> c.name().equals(list.get(0))
.findAny().orElse(Country.Others);
This is assuming the first element of the list is the name as you specified.
A simpler solution using the ternary operators would be :
Country searchCountry(List<String> list) {
return list.contains("China") ? Country.China :
list.contains("USA") ? Country.USA : Country.Others;
}