本文介绍了Java8流map()函数中的附加括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在Java8中工作/测试流,并且遇到了非常令人沮丧的问题.我的代码可以很好地编译:
I'm working/testing streams in Java8 and come across very frustrating issue.I've got the code which compiles well:
List<String> words = Arrays.asList("Oracle", "Java", "Magazine");
List<String> wordLengths = words.stream().map((x) -> x.toUpperCase())
.collect(Collectors.toList());
第二个(几乎相同)发出警告:
And second one (nearly the same) which throw a warnings:
List<String> words = Arrays.asList("Oracle", "Java", "Magazine");
List<String> wordLengths = words.stream().map((x) -> {
x.toUpperCase();
}).collect(Collectors.toList());
警告:
The method map(Function<? super String,? extends R>) in the type Stream<String> is not applicable for the arguments ((<no type> x) -> {})
这个额外的括号有什么变化?
What does this additional brackets have changed?
推荐答案
您的lambda表达式返回一个值.如果使用方括号,则需要在lambda函数中添加return语句:
Your lambda expression returns a value. If you use brackets you need to add a return statement to your lambda function:
List<String> words = Arrays.asList("Oracle", "Java", "Magazine");
List<String> wordLengths = words.stream().map((x) -> {
return x.toUpperCase();
}).collect(Collectors.toList());
这篇关于Java8流map()函数中的附加括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!