java8 List<Map> 转Map

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sessionsong/article/details/84103746

最近在做一个按天统计数据的功能的时候,需要将返回的一个 List 对象转换为map 返回给前端。

        List<Map> list = new ArrayList();
        Map map1 = new HashMap();
        map1.put("staticDay","11-15");
        map1.put("total","1");
        list.add(map1);
        map1 = new HashMap();
        map1.put("staticDay","11-16");
        map1.put("total","11");
        list.add(map1);
        map1 = new HashMap();
        map1.put("staticDay","11-17");
        map1.put("total","3");
        list.add(map1);
        map1 = new HashMap();
        map1.put("staticDay","11-18");
        map1.put("total","30");
        list.add(map1);
// 通过 java 8 的stream 变量list  能后通过get 方法取出数据并给新map 赋值
        Map resultMap = list.stream().collect(
                Collectors.toMap(s->s.get("staticDay"), s -> s.get("total")));

如果map 是一个对象 可以使用对象的getXxx() 方法来取值

 List<Person> personList = new ArrayList<>();
        personList.add(new Person(1,"aaaa"));
        personList.add(new Person(2,"bbbb"));
        personList.add(new Person(3,"cccc"));
        Map map = personList.stream().collect(Collectors.toMap(p->p.getId(),p->p.getName()));

更详细的操作可以参考: https://www.mkyong.com/java8/java-8-convert-list-to-map/

猜你喜欢

转载自blog.csdn.net/sessionsong/article/details/84103746