[英]Flattening a list of lists within a map
I have a stream of orders (the source being a list of orders). 我有订单流(来源是订单列表)。 Each order has a Customer, and a list of OrderLine. 每个订单都有一个Customer和一个OrderLine列表。
What I'm trying to achieve is to have a map with the customer as the key, and all order lines belonging to that customer, in a simple list, as value. 我想要实现的是在一张简单的列表中以客户为关键的地图,并将属于该客户的所有订单行作为值。
What I managed right now returns me a Map<Customer>, List<Set<OrderLine>>>
, by doing the following: 我现在管理的内容通过执行以下操作返回了Map<Customer>, List<Set<OrderLine>>>
:
orders
.collect(
Collectors.groupingBy(
Order::getCustomer,
Collectors.mapping(Order::getOrderLines, Collectors.toList())
)
);
I'm either looking to get a Map<Customer, List<OrderLine>>
directly from the orders stream, or by somehow flattening the list from a stream of the Map<Customer>, List<Set<OrderLine>>>
that I got above. 我正在寻找直接从订单流中获取Map<Customer, List<OrderLine>>
,或者通过某种方式Map<Customer>, List<Set<OrderLine>>>
我得到的Map<Customer>, List<Set<OrderLine>>>
流中的列表弄平以上。
Another option would be to use a simple forEach
call: 另一种选择是使用简单的forEach
调用:
Map<Customer, List<OrderLine>> map = new HashMap<>();
orders.forEach(
o -> map.computeIfAbsent(
o.getCustomer(),
c -> new ArrayList<OrderLine>()
).addAll(o.getOrderLines())
);
You can then continue to use streams on the result with map.entrySet().stream()
. 然后,您可以继续通过map.entrySet().stream()
在结果上使用流。
For a groupingBy
approach, try Flat-Mapping Collector for property of a Class using groupingBy 对于groupingBy
方法,请尝试使用groupingBy对类的属性进行Flat-Mapping Collector
You can simply use Collectors.toMap
. 您可以简单地使用Collectors.toMap
。
Something like 就像是
orders
.stream()
.collect(Collectors
.toMap(Order::getCustomer
, Order::getOrderLines
, (v1, v2) -> { List<OrderLine> temp = new ArrayList<>(v1);
temp.addAll(v2);
return temp;});
The third argument to the toMap
function is the merge function. toMap
函数的第三个参数是合并函数。 If you don't explicitly provide that and it there is a duplicate key then it will throw the error while finishing the operation. 如果您未明确提供该密码,并且有重复的密码,则它将在完成操作时引发错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.