gpt4 book ai didi

java - 如何在 LambdaJ 中创建值为 Collection 的 Map?

转载 作者:太空宇宙 更新时间:2023-11-04 06:45:00 25 4
gpt4 key购买 nike

我知道如何制作Map<String, Car>但如何制作Map<String, List<Car>>在 lambdaj 中?

这是我想在 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);
}

不幸的是代码:

Map<String, List<Car>> driverCarsMap = index(cars, on(Car.class).getDriver());

创建Map,但值没有被扩展而是被覆盖。因此,事实上我们确实注意到有一个 List,但只有一个对象。

最佳答案

您想要做的与 LambdaJ index 方法类似。索引的问题是它的局限性,它的文档说:

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()));

因此,您必须使用 LambdaJ 。对于您的示例,它将是:

Group<Car> group = group(cars, by(on(Car.class).getDriver()));

您可以在此处查看分组项目: https://code.google.com/p/lambdaj/wiki/LambdajFeatures#Grouping_items

关于java - 如何在 LambdaJ 中创建值为 Collection 的 Map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24125371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com