问题描述:

I'm trying to turn a List to a map, with key being each element of the list and the value being a new ArrayList.

Currently I'm doing this:

List<String> strLst = ...

Map<String, List<Foo>> map = strLst.stream()

.collect(Collectors.toMap(Function.identity(), _unused -> new ArrayList<>()));

Is there a better way than to do: _unused -> new ArrayList<>()?


To clarify my use case:

I have an API that takes in a list of resource Ids (i.e. this is List<String> strLst in example above) and I need to get the list of resources associated with each resource id (it's 1 to many mapping). It needs to return a map where the keyset of the map has all the resource Ids. The value for each resource Id is an empty list if the resource has no mapping. (but I want map.keySet to be equivalent to the original list)

I cannot do

for (String resourceId : allResourceIds) {

List<Result> results = getResults(resourceId);

map.put (resourceId, results)

}

because I need to call a bulk API for performance reasons

Map<String, List<Result>> map = ... // this is the step i'm trying to implement

List<Result> allResults = bulkGetResults(allResourceIds)

for (Result res : allResults) {

map.get(res.getResourceId()).add(res)

}

网友答案:

It looks like you first want to initiate an empty Map with an ArrayList of empty values and afterwards fill it with the result of your bulk call.

Depending on your situation you could combine these steps as follows:

Map<String, List<Result>> results = allResults.stream().collect(Collectors.groupingBy(Result::getResourceId));

If you are only interested in the resources returned by the bulk fetch, that should do it. If you really need an empty list when there is no result, you could solve that later on as a separate concern, e.g.

public List<Result> getResult(String resourceId){
    List<Result> resources = results.get(resourceId);
    return resources != null ? resources : Collections.emptyList();
}
相关阅读:
Top