微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Java 8 Optional for String of List作为输出

我想对返回List的方法使用Optional

让我们说功能

public Output getlistofSomething() {
    // In some cases there is nothing to return and hence it makes sense to have return 
    // type as Optional here
}

因此该函数看起来像:

public Optional<List<String>> getlistofSomething() {
    // return something only when there is some valid list
}

现在我想做一些事情,如果列表存在,如下所示:

Optional<List<String>> listofSomething = getlistofSomething();

int size = 0;

listofSomething.ifPresent(size = listofSomething.get().size());

我是Optional的新手,已经阅读了有关Optional的文章,看起来这应该可行但是我的IDE中出现语法错误

method ifPresent is not applicable for the arguments (void).

我想从开发人员那里获得一些帮助,他们可能会更熟练地使用java 8中的lamdas.

解决方法

真正的功能编程方式如下:
size = listofSomething.map(List::size).orElse(0);

但是返回一个空List而不是Optional会好得多.

原文地址:https://www.jb51.cc/java/128363.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐