相关疑难解决方法(0)

Java 8可选:ifPresent返回对象orElseThrow异常

我想做这样的事情:

 private String getStringIfObjectIsPresent(Optional<Object> object){
        object.ifPresent(() ->{
            String result = "result";
            //some logic with result and return it
            return result;
        }).orElseThrow(MyCustomException::new);
    }
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为ifPresent将Consumer功能接口作为参数,其具有void accept(T t).它不能返回任何值.还有其他办法吗?

java lambda optional

28
推荐指数
4
解决办法
7万
查看次数

Java 9 ifPresentOrElse 返回值

1/ 工作代码:

public Student process (int id, name){
  Optional<Student> studentOpt = myrepo.findById(id);
  studentOpt.isPresent() {
    return updateStudent(id, name);
  } else {
   return createStudent(id, name);
  }
Run Code Online (Sandbox Code Playgroud)

2/ 我尝试将其更改为“完整的 lambdas 代码”(不起作用):

public Student process (int id, name){
  Optional<Student> studentOpt = myrepo.findById(id);
  return studentOpt.ifPresentOrElse(student-> return updateStudent(id, name), () ->  return createStudent(id, name));
}
Run Code Online (Sandbox Code Playgroud)

1/ 我应该将其更改为完整的 lambda 吗?什么是最干净的?

2/ 如果是,如何?

java lambda optional java-9

6
推荐指数
1
解决办法
8836
查看次数

Java 10 ifPresentOrElse 返回布尔值

我对“如何正确执行此操作”有点困惑:

 // return true: if present and number of lines != 0
  boolean isValid(Optional<File> optFile) {
    return optFile.ifPresentOrElse(f -> return !isZeroLine(f), return false);
 }

 private boolean isZeroLine(File f)  {
    return MyFileUtils.getNbLinesByFile(f) == 0;
 }
Run Code Online (Sandbox Code Playgroud)

我知道语法不正确并且无法编译,但这只是为了让您了解这个想法。

我怎样才能把它变成“干净的代码”?即避免这样做:

if (optFile.isPresent()) {//} else {//}
Run Code Online (Sandbox Code Playgroud)

java lambda java-10 option-type

5
推荐指数
1
解决办法
6350
查看次数

标签 统计

java ×3

lambda ×3

optional ×2

java-10 ×1

java-9 ×1

option-type ×1