如何在分组时合并List <string>

时间:2019-02-24 06:03:28

标签: java grouping collectors

如何在List<String>期间合并groupingBy

给出一个自定义对象EligibilityRequest的列表,其中有一些重复项,我需要将EligibilityRequest的那些相等的实例分组,然后合并到String列表中,将特定属性有助于Equals方法。

这是详细信息:

public class EligibilityRequest {

 private String channel; // it's part of Equals
 ...

 private List<String> productCodes // it's not part of Equals and need to be aggregated within instance of EligibilityRequest "equal"

}

我尝试了以下操作:

  Map<EligibilityRequest, List<String>> uniqueEligibilityRequests = new HashMap<>();

  uniqueEligibilityRequests = requests.stream()
            .collect(groupingBy(request -> request,
                    Collectors.mapping(request -> request.getProductsCode(), toList())
                    ));

只要productCodes代表字符串而不是List<String>,它就起作用。我无法弄清楚如何在List<String>内合并不同的groupingBy

有人可以帮忙吗?

关于, 文森佐

2 个答案:

答案 0 :(得分:0)

您拥有的代码适用于创建值列表为列表的地图:

Map<EligibilityRequest, List<List<String>>> result = 
      requests.stream()
              .collect(groupingBy(request -> request,
                    Collectors.mapping(request -> request.getProductsCode(), 
                                       toList())
                ));

如果您的目的是将所有这些内部列表收集到一个列表中,那么您就需要用它来平整内部列表:

Map<EligibilityRequest, List<String>> res = 
        requests.stream()
        .collect(Collectors.groupingBy(Function.identity(),
                 Collectors.mapping(
                        EligibilityRequest::getProductCodes,
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                list -> list.stream()
                                            .flatMap(List::stream)
                                            .collect(Collectors.toList())))
                        )
                );

答案 1 :(得分:0)

在这种情况下,我发现无流代码更加舒适。

public static <K extends Comparable<K>> Map<K, Set<String>> groupBy(List<EligibilityRequest> requests, Function<EligibilityRequest, K> getKey) {
    Map<K, Set<String>> map = new TreeMap<>();

    for (EligibilityRequest request : requests) {
        map.compute(getKey.apply(request), (key, productCodes) -> {
            productCodes = productCodes == null ? new TreeSet<>() : productCodes;
            productCodes.addAll(request.getProductCodes());
            return productCodes;
        });
    }

    return map;
}