使用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会好得多.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...