原本的写法是:
Map<String, Object> map = new HashMap<>();
String text = "";
if(map.get("text")!=null){
    text = map.get("text").toString().trim();
}
System.out.println(text);

 

使用Java8的Lambda表达式则为:
Map<String, Object> map = new HashMap<>();
String text = Optional.ofNullable(map.get("text"))
        .flatMap((value) -> Optional.of(value.toString().trim()))
        .orElse("");
System.out.println(text);

 

或者使用map,就不需要手动包装成Optional了:

Map<String, Object> map = new HashMap<>();
map.put("text","123");
String text = Optional.ofNullable(map.get("text"))
        .map(value -> value.toString().trim())
        .orElse("");
System.out.println(text);

 

相关文章:

  • 2021-06-10
  • 2021-11-28
  • 2021-06-25
  • 2021-10-27
  • 2021-10-08
  • 2021-05-30
猜你喜欢
  • 2021-11-28
  • 2022-12-23
  • 2021-07-22
  • 2021-07-30
  • 2021-10-16
  • 2021-12-02
  • 2021-12-28
相关资源
相似解决方案