How to know which element matched in java-8 anymatch?

  • A+
Category:Languages

Assuming I have an enum

enum Country {     China,      USA,      Others } 

Say I have a list1 = ["China", "Shanghai", "Beijing"] and a check for isChina, if true, then return Country.China.

list2 = ["USA", "Dallas", "Seattle"] and a method checks for isUSA, if true then return Country.USA.

If USA or China is missing from the list, then return Country.Others.

Assumption: A list will always contain only 1 country followed by cities in that country.

While I find it extremely easy to implement in Java-7, I am not sure of the most elegant way to do this using streams

for (String str: list) {    if (str.equals("China")) {        return Country.China      }     if (str.equals("USA")) {        return Country.USA;     } } return Country.Other; 

I am looking for a clean implementation using Streams.

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: