如何在对对象列表应用groupby后获得单个对象而不是列表。

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

How to get an object instead of a list after applying groupingby on a list of Objects

问题

以下是翻译好的部分:

我正在对一个对象列表进行分组,如下面的代码所示:

Map<String, List<InventoryAdjustmentsModel>> buildDrawNumEquipmentMap = equipmentsAndCargoDetails.stream()
        .collect(Collectors.groupingBy(InventoryAdjustmentsModel::getBuildDrawNum));

现在我知道所有键的值只有一个元素,所以如何将它简化为:

Map<String, InventoryAdjustmentsModel>

而不必遍历所有键的元素或获取所有键的第一个元素。

英文:

I am doing a group by on a list of Objects as shown in the below code

Map&lt;String, List&lt;InventoryAdjustmentsModel&gt;&gt; buildDrawNumEquipmentMap = equipmentsAndCargoDetails.stream().
				collect(Collectors.groupingBy(InventoryAdjustmentsModel :: getBuildDrawNum));

Now I know the values for all the keys would have only one element, so how can I reduce it to just

Map&lt;String, InventoryAdjustmentsModel&gt;

instead of having to iterate through or get the 0th element for all the keys.

答案1

得分: 5

你可以使用带有合并函数的toMap收集器,如下所示。

Map<String, InventoryAdjustmentsModel> resultMap = equipmentsAndCargoDetails.stream()
    .collect(Collectors.toMap(InventoryAdjustmentsModel::getBuildDrawNum, 
        e -> e, (a, b) -> a));
英文:

You may use the toMap collector with a merge function like this.

Map&lt;String, InventoryAdjustmentsModel&gt; resultMap = equipmentsAndCargoDetails.stream().
    collect(Collectors.toMap(InventoryAdjustmentsModel::getBuildDrawNum, 
    	e -&gt; e, (a, b) -&gt; a));

答案2

得分: 2

尝试这样做。通过使用 toMap,您可以指定 keyvalue。由于您说没有重复的键,所以这不包括 merge 方法。这意味着如果发现重复的键,您将会收到一个错误。我认为这是您想要了解的信息。

Map<String, InventoryAdjustmentsModel> buildDrawNumEquipmentMap = 
    equipmentsAndCargoDetails.stream()
        .collect(Collectors.toMap(InventoryAdjustmentsModel::getBuildDrawNum, 
            model -> model));
英文:

Try it like this. By using toMap you can specify the key and the value. Since you said there were no duplicate keys this does not include the merge method. This means you will get an error if duplicate keys are discovered. Something I presumed you would want to know about.

Map&lt;String, InventoryAdjustmentsModel&gt; buildDrawNumEquipmentMap = 
                 equipmentsAndCargoDetails.stream().
            collect(Collectors.toMap(InventoryAdjustmentsModel::getBuildDrawNum, 
                     model-&gt;model));

</details>



huangapple
  • 本文由 发表于 2020年8月21日 22:54:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63525206.html
匿名

发表评论

匿名网友

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

确定