首页 > 解决方案 > 如何使用过滤器将 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 或其他东西。

标签: javaspring-bootspring-mvc

解决方案


您无需在代码上声明可迭代来过滤 ArrayList。filter 方法已经为您提供了一个。您可以使用:

subGoals = subGoals.stream().filter(subGoal ->
 /*Here goes your filter condition*/ ).collect(Collectors.toList());

推荐阅读