【发布时间】:2020-04-30 17:43:09
【问题描述】:
如何在没有任何循环或 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 ;
}
感谢帮助:)
【问题讨论】:
-
“没有任何循环、if 或迭代”——您可能不完全清楚流在后台是如何工作的
-
你试过什么?你被困在哪里了?请尝试,而不是要求我们为您编写代码。
-
new ArrayList()是一个 raw 泛型。不要使用 raw 泛型。 What is a raw type and why shouldn't we use it? --- 使用菱形运算符:new ArrayList<>()。 What is the point of the diamond operator (<>) in Java 7?
标签: java arraylist methods lambda collections