嵌套每个循环返回映射 Java 8 个流
Nested for each loop returning map with Java 8 streams
我刚开始使用 Java 8 和流,无法找到如何在 Java 8 中编写此代码:
Map<Integer, CarShop> result = new HashMap<>();
for (Car car : someListOfCars) {
List<CarProduct> listOfCarProducts = car.getCarProducts();
for (CarProduct product : listOfCarProducts) {
result.put(product.getId(), car.getCarShop());
}
}
有什么帮助吗?
您通常可以使用 .collect
:
将迭代解决方案直接转换为流
Map<Integer, CarShop> result = someListOfCars.stream().collect(
HashMap::new,
(map, car) -> car.getCarProducts().forEach(
prod -> map.put(prod.getId(), car.getCarShop())
),
Map::putAll
);
您可以以额外分配为代价使解决方案更加灵活:
Map<Integer, CarShop> result = someListOfCars.stream()
.flatMap(car -> car.getCarProducts().stream()
.map(prod -> new SimpleImmutableEntry<>(prod.getId(), car.getCarShop()))
).collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b));
这将允许您以任何您希望的方式收集。例如,如果有重复的 ID,您可以删除 (a,b)->b
以强制抛出异常,而不是默默地覆盖该条目。
我刚开始使用 Java 8 和流,无法找到如何在 Java 8 中编写此代码:
Map<Integer, CarShop> result = new HashMap<>();
for (Car car : someListOfCars) {
List<CarProduct> listOfCarProducts = car.getCarProducts();
for (CarProduct product : listOfCarProducts) {
result.put(product.getId(), car.getCarShop());
}
}
有什么帮助吗?
您通常可以使用 .collect
:
Map<Integer, CarShop> result = someListOfCars.stream().collect(
HashMap::new,
(map, car) -> car.getCarProducts().forEach(
prod -> map.put(prod.getId(), car.getCarShop())
),
Map::putAll
);
您可以以额外分配为代价使解决方案更加灵活:
Map<Integer, CarShop> result = someListOfCars.stream()
.flatMap(car -> car.getCarProducts().stream()
.map(prod -> new SimpleImmutableEntry<>(prod.getId(), car.getCarShop()))
).collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b));
这将允许您以任何您希望的方式收集。例如,如果有重复的 ID,您可以删除 (a,b)->b
以强制抛出异常,而不是默默地覆盖该条目。