java - 如何使用过滤器将 Iterable 更改为 ArrayList
问题描述
我有代码:
@GetMapping("/goal/{id}")
public String goalInfo(@PathVariable(value = "id") long id, Model model) {
if (!goalRepository.existsById(id)) {
return "redirect:/goal";
}
Iterable<SubGoal> subGoal = subGoalRepository.findAll();
ArrayList<SubGoal> subGoals = new ArrayList<>();
//How refactor this?
for(SubGoal sub : subGoal){
if(sub.getParentGoal().getId().equals(id)){
subGoals.add(sub);
}
}
if(subGoals.size() > 0) {
goalPercent(id, subGoal);
}
Optional<Goal> goal = goalRepository.findById(id);
ArrayList<Goal> result = new ArrayList<>();
goal.ifPresent(result::add);
model.addAttribute("goal", result);
model.addAttribute("subGoal",subGoals);
return "goal/goal-info";
}
在这里,我从存储库中获取子目标并过滤这些值。
没有foreach我怎么能做到?我想使用 Streams 或其他东西。
解决方案
您无需在代码上声明可迭代来过滤 ArrayList。filter 方法已经为您提供了一个。您可以使用:
subGoals = subGoals.stream().filter(subGoal ->
/*Here goes your filter condition*/ ).collect(Collectors.toList());
推荐阅读
- android - Unity 2020.1.3f1 won't build Android Project...完全卡住无法解决这些错误
- javascript - 无法在离线模式下打开 html
- c++ - 这个 randfloat() 有什么作用?
- hbase - HBase CheckAndMutate 是原子的,它也是一致的吗?
- javascript - 剑道验证失败但没有错误
- nginx - 由于 nginx 反向代理配置,Artifactory 下载过早终止
- ios - Xamarin.iOS 的 SetUseSafeArea
- mysql - mysql 奇怪的行为像 false=string 是真的
- html - 使用 id 选择 td 然后添加类和删除类
- javascript - 具有多个用户的 NodeJS/ExpressJS 服务器中的可变存储限制?