I know how to make Map<String, Car>
but how to make Map<String, List<Car>>
in lambdaj?
This is code I want to write in LambdaJ:
Map<String, List<Car>> driverCarsMap = new HashMap<String, List<Car>>();
for (Car car : cars)
{
String driver = car.getDriver();
if (!driverCarsMap.containsKey(driver))
driverCarsMap.put(driver, new ArrayList<Car>());
driverCarsMap.get(driver).add(car);
}
Unfortunately the code:
Map<String, List<Car>> driverCarsMap = index(cars, on(Car.class).getDriver());
creates the Map, but value is not being extended but overwritten. So, de facto we do note have a List but single object.
What you want to do is similar to LambdaJ index method. The problem with index is its limitation, its documentation says:
The former index feature is enough in many cases, but it has at least 2 big limitations: it doesn't manage conflicts if 2 or more objects should be indexed on the same key value and it doesn't easily allow to index the objects in a multilevel hierarchy.
To overcome these constraints lambdaj provides a feature to (optionally hierarchically) group objects on the value of their properties. As usual the preferred (statically typed) way in lambdaj to choose an object's property is via the on construct, so to group a List of Persons based on their ages it is sufficient to write:
Group group = group(meAndMyFriends, by(on(Person.class).getAge()));
So, what you have to use is LambdaJ groups. For your example, it would be:
Group<Car> group = group(cars, by(on(Car.class).getDriver()));
You can take a look at grouping items here: https://code.google.com/p/lambdaj/wiki/LambdajFeatures#Grouping_items