英文:
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<String, List<InventoryAdjustmentsModel>> 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<String, InventoryAdjustmentsModel>
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<String, InventoryAdjustmentsModel> resultMap = equipmentsAndCargoDetails.stream().
collect(Collectors.toMap(InventoryAdjustmentsModel::getBuildDrawNum,
e -> e, (a, b) -> a));
答案2
得分: 2
尝试这样做。通过使用 toMap,您可以指定 key 和 value。由于您说没有重复的键,所以这不包括 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<String, InventoryAdjustmentsModel> buildDrawNumEquipmentMap =
equipmentsAndCargoDetails.stream().
collect(Collectors.toMap(InventoryAdjustmentsModel::getBuildDrawNum,
model->model));
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论