将地图转换为地图列表

时间:2018-11-13 11:54:12

标签: java java-8 java-stream collectors

我有一个要把地图转换成地图列表的要求。

我尝试了以下代码

List<Map<String, Object>> response = new ArrayList<>();
Set<Long> categories = new HashSet<>();

List<CCP> ccpList = ccpRepository.findByPIdIn(ids);
Map<Integer, List<Integer>> categoriesByProduct = ccpList.stream()
                  .collect(Collectors.groupingBy(ccp -> ccp.getPId(), Collectors.mapping(ccp-> ccp.getCId(), Collectors.toList())));
for(Entry<Integer, List<Integer>> en : categoriesByProduct.entrySet()) {
    Map<String,Object> responseObject = new HashMap<>();
    responseObject.put("pid", en.getKey());
    responseObject.put("categories",en.getValue());
    response.add(responseObject);
}

有什么方法可以修改Java 8风格的以下代码:

for(Entry<Integer, List<Integer>> en : categoriesByProduct.entrySet()) {
    Map<String,Object> responseObject = new HashMap<>();
    responseObject.put("pid", en.getKey());
    responseObject.put("categories",en.getValue());
    response.add(responseObject);
}

2 个答案:

答案 0 :(得分:4)

将for循环内容放入函数中,并将其与流一起使用:

DataContext

答案 1 :(得分:2)

您可以这样做

List<Map<String, Object>> result = categoriesByProduct.entrySet().stream()
    .map(e -> Stream
        .of(new AbstractMap.SimpleEntry<String, Object>("pid", e.getKey()),
            new AbstractMap.SimpleEntry<String, Object>("categories", e.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)))
    .collect(Collectors.toList());