I have a List<Computer>. Every Computer has a list of CPU and a hostname.
So,suppose I have:
List<Computer> computers
I can call
List<CPU> CPUs = computer.getCPUs();
and I can call
String hostname = computer.getHostName();
What I want to do is, using Streams, obtain a Map that contains as key the CPU and as String the hostname. Same CPU inside the same Computers will replicate the hostname.
How can I do that?
Pre Java8 code would be this:
public Map<CPU, String> getMapping(List<Computer> computers) {
Map<CPU, String> result = new HashMap<>();
for (Computer computer : computers) {
for (CPU cpu : computer.getCPUs()) {
result.put(cpu, computer.getHostname());
}
}
return result;
}
If your CPU class has a back-reference to it's Computer instance, then you can do this easily. First stream over all the computers, and flat-map with getCPUs, this will give you a Stream<CPU> of all CPUs. Then you can use Collectors.toMap to collect into a Map<CPU, String> using Function.identity for the key and a lambda extracting first the Computer and then the hostname from the CPU for the value.
In code:
computers.stream()
.flatMap(computer -> computer.getCPUs().stream())
.collect(Collectors.toMap(Function.identity(), cpu -> cpu.getComputer().getHostname()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With