Java将一个list<T>指定key转换成Map<list>

经常有这种,一个数据库里有多个字段,但是数据库只能返回一个list,你group分组了也没用。

然后你得到的是一个list,你想根据type分组,大概是这样

数据库返回的

[

{"name":"牛奶","desc":"吃了有力气","type":"食物"},

{"name":"猫耳朵","desc":"富含丰富油脂","type":"食物"},

{"name":"电脑","desc":"可以提升人的效率","type":"工具"},

{"name":"防滑鞋","desc":"可以增大摩擦力,在冰面不摔倒","type":"工具"}

]

我想要的

{

"食物":[

{"name":"牛奶","desc":"吃了有力气","type":"食物"},

{"name":"猫耳朵","desc":"富含丰富油脂","type":"食物"}

],

"工具":[

{"name":"电脑","desc":"可以提升人的效率","type":"工具"},

{"name":"防滑鞋","desc":"可以增大摩擦力,在冰面不摔倒","type":"工具"}

]

}

上代码

代码(参考调用)

taskService.convertListToMap(taskList,BoardTask::getType);

方法

    //传入一个list,返回一个指定key的list的map
    public static  Map> convertListToMap(List list, Function keyExtractor) {
        return list.stream()
                .collect(Collectors.groupingBy(keyExtractor));
    }

你可能感兴趣的:(java,list,windows)