I have the following problem: Given these classes,
class Person {
private String zip;
...
public String getZip(){
return zip;
}
}
class
Some of the other answers contain code that does a lot of linear searching through lists. I think the Java 8 Stream solution should not be much slower than the classical variant. So here is a solution that takes advantage of Streams without sacrificing much performance.
List people = ...
List regions = ...
Map> zipToRegions =
regions.stream().collect(
() -> new HashMap<>(),
(map, region) -> {
for(String zipCode: region.getZipCodes()) {
List list = map.get(zipCode);
if(list == null) list = new ArrayList<>();
list.add(region);
map.put(zipCode, list);
}
},
(m1, m2) -> m1.putAll(m2)
);
Map> personToRegions =
people.stream().collect(
Collectors.toMap(person -> person,
person -> zipToRegions.get(person.getZip()))
);