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;
}
computerandcomputers. If you want your question to survive add pre-Java 8 code that accomplishes your task.