2

I have a List of String and I wanted to check if any of the String in the list matches the value of the ENUM. So I have done this. The boolean works fine. But I wanted to find the matching element from the list (first match).

boolean isMatch = Arrays.stream(MyEnum.values())
                        .map(MyEnum::getValue)
                        .anyMatch(myList::contains);
if(isMatch){
//get that matching string from the list .. i.e first matching string
}
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Jeeppp
  • 1,553
  • 3
  • 17
  • 39
  • to complete the problem, what also matters is the `else` part of the code that hasn't been shared, but the approach is detailed in the linked Q&As. – Naman Jul 07 '20 at 17:03

2 Answers2

1

You can filter and get the first one using .findFirst().

Optional<MyEnum> res = Arrays.stream(MyEnum.values())
                        .filter(e -> myList.contains(e.getValue()))
                        .findFirst();

if(res.isPresent()){
   MyEnum data = res.get(); // matched enum
}
Eklavya
  • 17,618
  • 4
  • 28
  • 57
  • 1
    the `else` part holds the significance to some extent in deciding if the solution could complete with `ifPresent` vs `orElse...` API from `Optional` – Naman Jul 07 '20 at 17:16
  • @Naman Definitely, I tried to give a solution with the info provided by OP – Eklavya Jul 07 '20 at 17:32
0

You could do it like this:

public static void main(String[] args) {
    List<String> list = Arrays.asList("A", "B", "Test", "D");

    Optional<String> match = list.stream().filter(str -> str.equals(Value.Test.name())).findFirst();
    if (match.isPresent()) {
        // do something with the match
        String str = match.get();
        System.out.println(str);
    }
}

private enum Value {
    Test
}
fose
  • 730
  • 1
  • 10
  • 24