-2

I'm trying to verify if my list myList getName() contains at least one value of a set names. I created a method for it, but I'm wondering if there is a simpler way in Java.

private boolean validateMyList(List<myObject> myList, Set<String> names) {
   for(myObject obj : myList) {
      if(names.contains(obj.getName())) {
         return true;
      }
   }
   return false;
}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
myTest532 myTest532
  • 2,091
  • 3
  • 35
  • 78

1 Answers1

2
return myList.stream()            // Stream<myObject>
    .map(myOject::getName)        // Stream<String>
    .anyMatch(names::contains);   // boolean

That is a Stream solution, though not necessarily faster.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138