如何通过枚举类型在Java 8中合并多个列表?
我有2个清单:

List<StatusSummary> listA //4 items because we have 4 enum types
List<StatusSummary> listB //4 items because we have 4 enum types

class StatusSummary {
  private StatusEnum resourcesStatus; //4 statuses: TypeA, TypeB, TypeC, TypeD
  private Integer count;
}
我想为每个resourcesStatus: TypeA, TypeB, TypeC, TypeD提供一个包含4个项目的列表,并在count字段中添加元素的总和,例如:
List<StatusSummary> listA+B with 4 objects:
(resourcesStatus: TypeA, count: 3), (resourcesStatus: TypeB, count:99), (resourcesStatus: typeC, count:322), (resourcesStatus: TypeD, count:2)
到目前为止,我实现了以下内容:
listA
    .getResourcesStatus()
    .forEach(la -> listB.getResourcesStatus().stream()
        .filter(lb -> lb.getResourcesStatus() == la.getResourcesStatus())
        .forEach(lb -> result.add(new StatusSummary()
            .count(la.getCount() + lb.getCount())
        .status(la.getStatus()))));

最佳答案

您可以使用Collectors.toMap。通过ResourcesStatus映射,并在merge-function中将两个StatusSummarycount字段合并为相同的ResourcesStatus,然后获取Map<StatusEnum, StatusSummary>,然后使用.values()中的ArrayList获取地图的值。

List<StatusSummary> newList =
           new ArrayList<>(
                  Stream.of(listA, listB)
                 .flatMap(Collection::stream)
                 .collect(Collectors.toMap(e -> e.getResourcesStatus(), i -> i,
                   (a,b) -> new StatusSummary(a.getResourcesStatus(),
                                                a.getCount() + b.getCount())))
                 .values());

09-28 01:51