I'm looking for an efficient design pattern to map one list of objects to another list of objects with zero-or-one-to-one relationships between them. I realize this sort of thing is typically done in a relational database, but in this particular case it really needs to be done in the Java application...
Let's say the first list contains Foo objects (i.e. List<Foo>):
public class Foo {
public Integer id;
public String barName;
}
And the second list contains Bar objects (i.e. List<Bar>):
public class Bar {
public Integer fooId;
public String name;
}
How can I most efficiently map all name properties from Bar to the Foo object where Bar.fooId equals Foo.id?
The best I can think of is this:
void mapFooBar(List<Foo> fooList, List<Bar> barList) {
for (Bar bar : barList) {
for (Foo foo : fooList) {
if (bar.fooId.equals(foo.id)) foo.barName = bar.name;
}
}
}
EDIT: Based on several answers, I have improved my code as follows:
void mapFooBar(List<Foo> fooList, List<Bar> barList) {
Map<Integer, String> barMap = new HashMap<Integer, String>();
for (Bar bar : barList)
barMap.put(bar.fooId, bar.name);
for (Foo foo : fooList)
if (barMap.containsKey(foo.id)) foo.barName = barMap.get(foo.id);
}
Is there a better way?
Mapinterface?