(Predicate<? super String> s) or (String s)

  • A+

I have a TreeSet of Strings (hardcoded). Want to check that a given parameter String eg. "Person" if present in the TreeSet then return true otherwise return false.

Here I am confused by the Eclipse message regarding (Predicate<? super String> s) vs (String s):

The method anyMatch(Predicate) in the type Stream is not applicable for the arguments (String)

Please guide.

import java.util.Set; import java.util.TreeSet; import java.util.function.Predicate;  public class SystemLabelValidator {      public static boolean ValidateSystemLabel( String s) {            String j = s;          boolean b = false;          Set <String> SystemLabels = new TreeSet<String>();         // Unique Strings         SystemLabels.add("Person");         SystemLabels.add("Player");         SystemLabels.add("Hospital");         SystemLabels.add("Nurse");         SystemLabels.add("Room");          System.out.println("/n==> Loop here.");         for (String temp : SystemLabels) {             System.out.println(temp);              if(SystemLabels.stream().anyMatch(j)) {                 System.out.println("I need to return Boolean");             }             return b;         }         return b;     } } 


There is no need to use a Predicate here. In order to check if the String is present in your TreeSet just use :

return systemLabels.contains("Person"); 

If you still insist on using anyMatch then you can do :

public static boolean validateSystemLabel(String s) {     return systemLabels.stream().anyMatch(i -> i.equals(s)); } 

Remember, a predicate expression needs to evaluate to a boolean value but in the code, you are passing in a String hence the compilation error.


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