将对象列表转换为对象映射。

huangapple go评论57阅读模式
英文:

Convert list of object to map of object

问题

将以下代码从对象列表转换为对象映射的 Java 流代码如下:

List<OrderData> orderList = getOrderList();
Map<String, OrderData> orders = orderList.stream()
        .filter(order -> orderData == null || !order.getFiles().isEmpty())
        .collect(Collectors.toMap(OrderData::getOrderID, Function.identity()));

这是你要求的代码翻译。如果需要更多帮助,请告诉我。

英文:

How do I convert the following code below from list of objects to map of objects using Java stream?

List&lt;OrderData&gt; orderList = getOrderList();
Map&lt;String, OrderData&gt; orders = new HashMap&lt;&gt;();

orderList.forEach(order -&gt; {
    OrderData orderData = orders.get(order.getOrderID());

    if (orderData == null || !order.getFiles().isEmpty()){
        orders.put(order.getOrderID(), order);
    }
});

答案1

得分: 1

这应该可以解决问题:

Map<String, OrderData> collect = orderList.stream()
                .filter(o -> !o.getFiles().isEmpty())
                .collect(Collectors.toMap(OrderData::getOrderID,
                                          Function.identity()));
英文:

This should do the trick:

Map&lt;String, OrderData&gt; collect = orderList.stream()
                .filter(o -&gt; !o.getFiles().isEmpty())
                .collect(Collectors.toMap(OrderData::getOrderID,
                                          Function.identity()));

答案2

得分: 0

以下是翻译好的部分:

根据 `@f1sh` 的代码添加了碰撞处理

Map<String, OrderData> collect = orderList.stream()
        .filter(o -> !ObjectUtils.isEmpty(o.getOrderID()) && !o.getFiles().isEmpty())
        .collect(Collectors.toMap(OrderData::getOrderID, Function.identity(), (k1, k2) -> k1));
英文:

Collision processing is added based on @f1sh's code:

Map&lt;String, OrderData&gt; collect = orderList.stream()
        .filter(o -&gt; !ObjectUtils.isEmpty(o.getOrderID()) &amp;&amp; !o.getFiles().isEmpty())
        .collect(Collectors.toMap(OrderData::getOrderID, Function.identity(), (k1, k2) -&gt; k1));

huangapple
  • 本文由 发表于 2023年4月7日 01:07:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952061.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定