StillLearningToCode StillLearningToCode - 6 months ago 9
Java Question

Java if else in a lambda expression

I am trying to use a lambda expression to evaluate to true or false on whether a input parameter to a method has a certain character '*' at the end of the string; as an input to a constructor to an object. im sure this is way off, but this is what i was trying to do before i looked around the web and saw some referring to using streams, but I'm not sure how or if they would work for this situation:

public void addPermission(String permission, String resource){
permissions.put(new Permission(permission,
()-> {if (permission.charAt(permissions.size() - 1) == '*') return true; }));
}


any input would be greatly appreciated.

Answer

Your lambda expression is missing an else case (or a final return), see this example:

public void addPermission(String permission, String resource){
  permissions.put(new Permission(permission, ()-> {
    if (permission.charAt(permissions.size() - 1) == '*') 
      return true;
    return false;
  }));
}

Note that this would not compile if permissions is a Map, because the signature of Map.put is not compliant.

Another simplification (beyond those already mentioned by others):

public void addPermission(String permission, String resource){
  permissions.put(new Permission(permission, ()-> permission.charAt(permissions.size() - 1) == '*'));
}

The type of the given lambda should be a FunctionalInterface with no argument and result Boolean, e.g. Supplier<Boolean>.

Comments