【Java8求助】 一个有关List<Map>对象进行flatMap()方法而后分组的问题

问题描述:有个List对象,如下:
List<Map<String,Object>> query = new ArrayList<Map<String,Object>>
Json视图下的例子数据为:
[

{
    "customer_attribute": "1",
    "customer_attribute_no": "0101019",
    "group_no": 1
},
{
    "customer_attribute": "2",
    "customer_attribute_no": "A001",
    "group_no": 1
},
{
    "customer_attribute": "3",
    "customer_attribute_no": "AA001",
    "group_no": 2
}

]
现在需求是将原List中数据构建成:
[

{
    "attributelist": [
        {
            "customer_attribute": "1",
            "customer_attribute_no": "0101019"
        },
        {
            "customer_attribute": "2",
            "customer_attribute_no": "A001"
        }
    ],
    "group_no": 1
},
{
    "attributelist": [
        {
            "customer_attribute": "3",
            "customer_attribute_no": "AA001"
        }
    ],
    "group_no": 2
}

],
我的想法是将原来的List中的多个Map先用stream中的flatMap()合成一个Map,让后对这个Map中以“group_no”为key进行分组,分组后将各自新Map中的“customer_attribute”构建新的key为“attributelist”的List,从而实现。但我太清楚具体该如何编写代码,有前辈可以指导写一下参考吗?万分感激!

阅读 6.8k
2 个回答

分组可以用GroupingBy方法,以下是参考代码

List<Map<String, Object>> result = query.stream().collect(Collectors.groupingBy(e -> e.get("group_no")))
                .entrySet().stream().map(e -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("attributelist", e.getValue());
                    map.put("group_no", e.getKey());
                    return map;
                }).collect(Collectors.toList());

我java8的stream也不是很熟,这样能满足要求,但是不知道还有没有更简单的写法。

// init data
List<Map<String,Object>> query = new ArrayList<>();
HashMap<String, Object> e1 = new HashMap<>();
e1.put("group_no",1);
e1.put("customer_attribute","1");
e1.put("customer_attribute_no","0101019");
query.add(e1);

HashMap<String, Object> e2 = new HashMap<>();
e2.put("group_no",1);
e2.put("customer_attribute","2");
e2.put("customer_attribute_no","A001");
query.add(e2);

HashMap<String, Object> e3 = new HashMap<>();
e3.put("group_no",2);
e3.put("customer_attribute","3");
e3.put("customer_attribute_no","A002");
query.add(e3);

// stream
List<HashMap<String, Object>> group_no = query.stream()
        .collect(Collectors.groupingBy(q -> q.get("group_no")))
        .entrySet()
        .stream()
        .map(e -> {
            HashMap<String, Object> inner = new HashMap<>();
            List<Map<String, Object>> newList = e.getValue().stream().map(v -> {
                v.remove("group_no");
                return v;
            }).collect(Collectors.toList());
            inner.put("attributelist", newList);
            inner.put("group_no",e.getKey());
            return inner;
        }).collect(Collectors.toList());

System.out.println(JSON.toJSONString(group_no));
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题