I am struggling to convert an existing forloop to a lambda expression.
I have a list of objects (List<Task>
) which contains a map called 'InputData' (Map<String, String>
).
I also have another Map<String, String>
(Acceptance).
I want to filter the list of Task objects where the Task.InputData Map contains all the 'Acceptance' map entries. Task.InputData may contain additional entries but I want to enforce the vars that exist in Acceptance must exist in Task.InputData.
The existing for loop looks like so:
boolean addTask;
List<Task> finalResults = new ArrayList<>();
for (Task t : results) {
addTask = true;
for (Entry<String, String> k : kvVars.entrySet()) {
if (!t.getInputData().containsKey(k) || !t.getInputData().get(k).equals(k.getValue())) {
addTask = false;
}
}
if (addTask) {
finalResults.add(t);
}
}
I'm a bit confused about an approach, whether I should be trying to combine flatmap and filter criteria or if I should follow the logic in the existing for loop.
You can use the filter
to collect all Task
's that having all the 'Acceptance' k/v in InputData
List<Task> finalResults = results.stream()
.filter(t->kvVars.entrySet()
.stream()
.allMatch(k->t.getInputData().containsKey(k.getKey())
&& t.getInputData().get(k.getKey()).equals(k.getValue()))
.collect(Collectors.toList());