Abh*_*yer 2 java-8 java-stream
我上课了
class Person {
String name;
....
Optional<Integer> children;
}
Run Code Online (Sandbox Code Playgroud)
如何使用流来获取所有孩子的总数?
public int totalCount(final Set<Person> people) {
int total = 0;
for (Person person : people) {
if (person.getChildren().isPresent()) {
total += person.getChildren().get();
}
}
return total;
}
Run Code Online (Sandbox Code Playgroud)
如何使用Java 8流做到这一点?
public int totalCount(final Set<Person> people) {
int total = 0;
people.stream()
.filter(p -> p.getChildren().isPresent())
// ???
}
Run Code Online (Sandbox Code Playgroud)
替代方案:
int sum = people.stream().mapToInt( p -> p.getChildren().orElse(0) ).sum();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
850 次 |
| 最近记录: |