5

如何使用Lambda表达式对Map进行分组?

有如下数据

我想对该数据进行分组(按camp阵营进行分组)

但是我不知道该怎么写,求大神指教

package com.renguanyu.demo.lambda;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Data {

    public static List<Map<String,Object>> getSanGuoMaps(){
        List<Map<String,Object>> maps = new ArrayList<>();
        Map<String,Object> map1 = new HashMap<>();
        map1.put("id", 1);
        map1.put("name", "刘备");
        map1.put("height", 175.01);
        map1.put("camp", "蜀");
        Map<String,Object> map2 = new HashMap<>();
        map2.put("id", 2);
        map2.put("name", "关羽");
        map2.put("height", 180.00);
        map2.put("camp", "蜀");
        Map<String,Object> map3 = new HashMap<>();
        map3.put("id", 3);
        map3.put("name", "张飞");
        map3.put("height", 190.00);
        map3.put("camp", "蜀");
        Map<String,Object> map4 = new HashMap<>();
        map4.put("id", 4);
        map4.put("name", "吕布");
        map4.put("height", 190.00);
        map4.put("camp", "其他");

        maps.add(map1);
        maps.add(map2);
        maps.add(map3);
        maps.add(map4);

        return maps;
    }
}

package com.renguanyu.demo.lambda;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Demo1 {

    public static void main(String[] args) {
        List<Map<String, Object>> sanGuoMaps = Data.getSanGuoMaps();
        System.out.println(sanGuoMaps);
//      sanGuoMaps.stream().collect(Collectors.groupingBy(Map::get("name")));
    }
}

查看全部
u013179958
CSDNRGY
2019/03/30 10:41
  • java
  • 点赞
  • 收藏
  • 回答
    私信

2个回复