You want a Map<Worker,Set<Employer>>
for this, or possibily a Multimap<Worker,Employer>
from Guava.
In pseudocode:
initialize employerMap(worker => set of employers)
for every employer n do
for every worker x in n.workers do
employerMap[x].add(n)
Essentially a Worker
can be mapped to multiple Employer
, so you either:
- Have a
Map<Worker,Set<Employer>>
- each key in a
Map
can only have one value, so the value in this case is a Set
of values
- Have a
Multimap<Worker,Employer>
Multimap
can map a key to multiple values
Example
Here's an example of doing the mapping. Note that storing the data in Object[][] arr
like this is definitely not recommended, and is only used as part of the example. Concentrate on the actual mapping part.
import java.util.*;
public class MultiMapExample {
public static void main(String[] args) {
Object[][] arr = {
{ "IBM", new String[] { "Joe", "Jack", "Carol" }},
{ "MS", new String[] { "Jack", "Andy", "Carol" }},
{ "Google", new String[] { "Bob", "Alice", "Carol" }},
};
Map<String,Set<String>> employerMap =
new HashMap<String,Set<String>>();
for (Object[] data : arr) {
String employer = (String) data[0];
String[] workers = (String[]) data[1];
for (String worker : workers) {
Set<String> employers = employerMap.get(worker);
if (employers == null) {
employerMap.put(worker, employers = new HashSet<String>());
}
employers.add(employer);
}
}
for (String worker : employerMap.keySet()) {
System.out.println(worker + " works for " + employerMap.get(worker));
}
}
}
This prints (order may vary):
Alice works for [Google]
Jack works for [IBM, MS]
Bob works for [Google]
Andy works for [MS]
Carol works for [IBM, Google, MS]
Joe works for [IBM]
I recommend keeping the data in a Map
like this, but if you must transform the list of employees to an array for some reason, you can use Collection.toArray(T[])
.
You should generally prefer List
and other Java Collections Framework classes to arrays, though.
On implementing equals
, hashCode
, etc
The above example uses String
for simplicity. You probably should have an actual Worker
and Employer
types instead, which is a good thing. You have to make sure that they implement equals
and hashCode
properly, though.
See also
- Effective Java 2nd Edition
- Item 8: Obey the general contract when overriding equals
- Item 9: Always override hashcode when you override equals
API links
Related questions
On equals/hashCode
combo:
On equals
vs ==
: