我处于一种奇怪的情况下,其中有一个JSON API,该数组将以邻域字符串作为键的数组和以餐厅字符串作为值的数组,将GSON解析为Restaurant对象(String为邻域定义了A List<String>,餐馆)。系统将该数据存储在地图中,该地图的键是社区名称,值是该社区中的一组餐厅名称。因此,我想实现一个函数,该函数接收来自API的输入,按邻域对值进行分组,并连接餐馆列表。
受Java 8的约束,我无法使用更新的构造(例如flatMapping)在一行中完成所有操作,而我发现的最佳解决方案是此解决方案,该解决方案在连接这些列表之前使用中间映射存储一组List放入Set中以作为值存储在最终映射中:
public Map<String, Set<String>> parseApiEntriesIntoMap(List<Restaurant> restaurants) {
if(restaurants == null) {
return null;
}
Map<String, Set<String>> restaurantListByNeighborhood = new HashMap<>();
// Here we group by neighborhood and concatenate the list of restaurants into a set
Map<String, Set<List<String>>> map =
restaurants.stream().collect(groupingBy(Restaurant::getNeighborhood,
Collectors.mapping(Restaurant::getRestaurantList, toSet())));
map.forEach((n,r) -> restaurantListByNeighborhood.put(n, Sets.newHashSet(Iterables.concat(r))));
return restaurantListByNeighborhood;
}
Run Code Online (Sandbox Code Playgroud)
我觉得必须有一种方法可以摆脱该中间图,并一站式完成所有工作……某人是否有更好的解决方案可以让我做到这一点?