java - Java Collection 方法到 lambda 方法
问题描述
如何在没有任何循环或 if 的情况下将此方法更改为 lambda?
public Collection<String> test (Collection<String> strings) {
ArrayList<String> arrayListOfStrings = new ArrayList();
for(String str : strings) {
if(str.length() >= 10) {
String s = str.substring(str.length() / 2);
if(s.charAt(0) >= 'a') {
arrayListOfStrings.add(s.toUpperCase());
}
}
}
return arrayListOfStrings;
}
我已经尝试过这种方式,有人得到了另一个或更好的解决方案吗?:
public Collection<String> test (Collection<String> strings) {
ArrayList<String> arrayListOfStrings = new ArrayList<String>();
Stream<String> myStream = strings.stream()
.filter(str -> str.length() >= 10)
.map(str -> str.substring(str.length()/2))
.filter(str -> str.charAt(0) >= 'a');
myStream.forEach(str -> arrayListOfStrings.add(str.toUpperCase()));
return arrayListOfStrings ;
}
谢谢帮助:)
解决方案
您应该使用以下collect()
方法Collectors.toList()
:
public Collection<String> test(Collection<String> strings) {
return strings.stream()
.filter(str -> str.length() >= 10)
.map(str -> str.substring(str.length() / 2))
.filter(s -> s.charAt(0) >= 'a')
.map(String::toUpperCase)
.collect(Collectors.toList());
}
你的问题说:
没有任何循环或 if 的
但是您应该知道filter()
使用if
语句,并collect()
使用循环来迭代流的元素,因此您还没有消除“循环或 if”,您只是将该逻辑委托给流框架。
推荐阅读
- python - python:循环遍历Excel中的索引并用字符串替换
- angular - Angular 7 - 从 Angular 组件生成 URL
- c# - C# 按时间更改表行类
- rest - OAuth2 用于 REST API,紧耦合 SPA 作为唯一客户端
- python - 在 Jupyter 中写入目录权限
- python - 有没有办法使用 Wand(ImageMagick Python 绑定)修剪透明区域?
- bootstrap-4 - 如何更改 bootstrap 4.1 scrollspy(moving) 活动链接颜色?
- javascript - 代码荧光笔在羽毛笔编辑器中不起作用
- vuejs2 - 如何使用 VueJS axios-oauth-client 和 google photos api?
- flask - 将 JSON 从 Places Autocomplete 发送到 Flask