简体   繁体   English

Java(如果不是)在lambda表达式中

[英]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; 我正在尝试使用lambda表达式对方法的输入参数在字符串的末尾是否具有特定字符'*'求值为true或false; 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. 任何投入将不胜感激。

Do you need to use streams for this? 需要为此使用流吗? Homework, bet, whatever? 功课,打赌,什么?

If you don't 如果你不这样做

A plain old checking on the String with the endsWith() method would suffice. endsWith()方法对String进行简单的旧检查就足够了。

public void addPermission(String permission, String resource){
    permissions.put(new Permission(permission, permission.endsWith("*")));
}

If you want to play around with lambdas 如果您想玩Lambdas

You can provide a way to tell the constructor what type of checking it needs to do in order to fill in that flag. 您可以提供一种方法来告诉构造函数填写该标志所需执行的检查类型。

Constructor: 构造函数:

public Permission(String permission, Predicate<String> checker) {
    this.permission = permission;
    this.flag = checker.test(permission);
}

Caller: 呼叫者:

new Permission(permission, (p) -> p.endsWith("*"));

Your lambda expression is missing an else case (or a final return), see this example: 您的lambda表达式缺少else情况(或最终返回),请参见以下示例:

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. 请注意,如果permissions是Map,则不会编译,因为Map.put的签名不符合要求。

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 , eg Supplier<Boolean> . 给定lambda的类型应为无参数且结果为BooleanFunctionalInterface ,例如Supplier<Boolean>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM