java 8 中的 Lambda 表达式(使用 java.util.Optional 在 HashMap 中进行空检查)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31558848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lambda expression in java 8 (Null check in HashMap using java.util.Optional)
提问by Raghu
I'm new to java 8 and learning lambda expression.
我是 Java 8 的新手,正在学习 lambda 表达式。
I have an interface.
我有一个接口。
Configuration.java
配置文件
package com.raghu.example;
import java.util.Map;
public interface Configuration {
public Map<String,String> getPayload();
}
Impl for interface: ConfigurationImpl.java
接口的Impl:ConfigurationImpl.java
package com.raghu.example;
import java.util.HashMap;
import java.util.Map;
public class ConfigurationImpl implements Configuration {
@Override
public Map<String, String> getPayload() {
Map<String,String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
//return null;
return map;
}
}
My Main Program : Sample.java
我的主程序:Sample.java
package com.raghu.example;
import java.util.Optional;
public class Sample {
Configuration config;
/*
* if config is null, return "";
* if config.getPaylaod is null, return "";
* if config.payload is not null and if key value is present, then return the value
* if config.payload is not null and if invalid key, then return "";
*
*/
String test(String key) {
config = new ConfigurationImpl();
String dataValue = "";
/** java 7
if (StringUtils.isNotEmpty(key)) {
try {
String input= config.getPayload()==null?"":config.getPayloadmap().get(key);
return (input!=null?input:"");
} catch (Exception e) {
return "";
}
}
return "";
}**/
Optional.ofNullable(config).map(Configuration::getPayload).ifPresent(v->{final String str=v.get(key);System.out.println(str);});
// //cdataValue=str;});
// //Optional.ofNullable(config).map(Configuration::getPayload).ifPresent(v->{final String str=v.get(key);System.out.println(str);return str;});
return dataValue;
}
public static void main(String[] args) {
Sample s = new Sample();
String value="";
value=s.test("key"); //pass invalid , should return "";
System.out.println(value);
value=s.test("key1"); //pass invalid , should return actual value
System.out.println(value);
}
}
Now in the method test, i want to do the following[""].
现在在方法测试中,我想做以下[""]。
- Check if config is null, return empty String.
- Check if collection is null, return empty string.
- If collection is not null, and if key is present, then return the value else return "";
- 检查 config 是否为空,返回空字符串。
- 检查集合是否为空,返回空字符串。
- 如果 collection 不为 null,并且存在 key,则返回值 else return "";
How to do this in java 8?
如何在 Java 8 中做到这一点?
Tried this:
试过这个:
Error 1:Void methods cannot return a value
Optional.ofNullable(config).map(Configuration::getPayload).ifPresent(v->{final String str=v.get(key);System.out.println(str);return str;});
Error 2: Local variable dataValue defined in an enclosing scope must be final or effectively final.
Optional.ofNullable(config).map(Configuration::getPayload).ifPresent(v->{final String str=v.get(key);System.out.println(str);dataValue= str;});
错误 1:void 方法不能返回值
Optional.ofNullable(config).map(Configuration::getPayload).ifPresent(v->{final String str=v.get(key);System.out.println(str);return str;});
错误 2:在封闭作用域中定义的局部变量 dataValue 必须是最终的或有效的最终的。
Optional.ofNullable(config).map(Configuration::getPayload).ifPresent(v->{final String str=v.get(key);System.out.println(str);dataValue= str;});
Adding final doesn't solve.
添加final并不能解决。
Also posted the java 7 code and I'm trying to solve the if-else part of java 7 with lambda expression.
还发布了 java 7 代码,我正在尝试使用 lambda 表达式解决 java 7 的 if-else 部分。
回答by Misha
You can just keep on chaining .map(...)
. If null happens at any of the steps, it will just make the whole thing into an empty Optional
and then orElse("")
will return the default value.
你可以继续链接.map(...)
。如果在任何步骤中发生 null,它只会使整个事情变为空Optional
,然后orElse("")
将返回默认值。
return Optional.ofNullable(config)
.map(Configuration::getPayload)
.map(c->c.get(key))
.orElse("");