I have the following nested for loop that I want to convert to use a stream instead as I am currently learning to use streams, how can I do so?
I have added my current attempt below but it is currently incomplete.
Part part = getPart();
List<Machines> machines = new ArrayList<>();
List<String> identities = getMachineIdentities();
Set<MachinePart> machineParts = new HashSet<>();
//create machines
for (String identity : identities) {
Machine machine = getMachine(identity);
machines.add(machine);
}
//map to MachineParts
for (Machine machines : machines) {
MachinePart machinePart = MachinePartCreator.new(machines, part);
machineParts.add(machinePart);
}
Stream attempt:
Set<MachinePart > machineParts = identities.stream()
.map(identity-> ??? ).collectors.collect(Collectors.toSet()));
Your first loop creates the input for the second loop. This can be achieved with two map()
calls:
Set<MachinePart> machineParts =
identities.stream()
.map(id -> getMachine(id))
.map(m -> MachinePartCreator.new(m, part))
.collect(Collectors.toSet());
Or even one:
Set<MachinePart> machineParts =
identities.stream()
.map(id -> MachinePartCreator.new(getMachine(id),part))
.collect(Collectors.toSet());
Of course, you can also write the original code with a single for loop and skip the intermediate List<Machines> machines
.