Search code examples
javajava-streamnested-loops

Convert nested foreach loops into a Stream


I want to refactor nested for loops in the following code with streams:

private List<Task> readHistoryFromFile() {

        List<Task> tasks = new ArrayList<>();

        for (String s : readFromCsvHistoryFromFile()) { // List<String>
            for (Task task : fromString()) { // List<Task>

                if (task.getId().toString().equals(s)){
                    tasks.add(task);
                }
            }
        }
        return tasks;
    }

What is the best and simplest way to do so


Solution

  • I have no idea what the code you are calling does because it's not in the question but try this:

    readFromCsvHistoryFromFile().stream()
        .flatMap(s -> fromString().stream()
                 .filter(task -> task.getId().toString().equals(s)))
        .toList();