How to check if element exists using lambda expression?

In particular, I have a TabPane, and I would like to know if there is an element with a specific identifier in it.

So, I would like to do this using the lambda expression in Java:

boolean idExists = false; String idToCheck = "someId"; for (Tab t : tabPane.getTabs()){ if(t.getId().equals(idToCheck)) { idExists = true; } } 
+54
java lambda java-8
Apr 11 '14 at 6:19 06:19
source share
2 answers

Try using anyMatch Lambda expressions. This is a much better approach.

  boolean idExists = tabPane.getTabs().stream() .anyMatch(t -> t.getId().equals(idToCheck)); 
+128
Apr 11 '14 at 6:24
source share

Although the accepted answer is correct, I will add a more elegant version (in my opinion):

 boolean idExists = tabPane.getTabs().stream() .map(Tab::getId) .anyMatch(idToCheck::equals); 

Do not neglect the use of Stream # map () , which allows you to smooth the data structure before applying Predicate .

+19
Dec 12 '16 at 19:45
source share



All Articles