经常有这种,一个数据库里有多个字段,但是数据库只能返回一个list,你group分组了也没用。
然后你得到的是一个list,你想根据type分组,大概是这样
数据库返回的
[
{"name":"牛奶","desc":"吃了有力气","type":"食物"},
{"name":"猫耳朵","desc":"富含丰富油脂","type":"食物"},
{"name":"电脑","desc":"可以提升人的效率","type":"工具"},
{"name":"防滑鞋","desc":"可以增大摩擦力,在冰面不摔倒","type":"工具"}
]文章来源:https://www.toymoban.com/news/detail-820840.html
我想要的
{
"食物":[
{"name":"牛奶","desc":"吃了有力气","type":"食物"},
{"name":"猫耳朵","desc":"富含丰富油脂","type":"食物"}
],
"工具":[
{"name":"电脑","desc":"可以提升人的效率","type":"工具"},
{"name":"防滑鞋","desc":"可以增大摩擦力,在冰面不摔倒","type":"工具"}
]
}文章来源地址https://www.toymoban.com/news/detail-820840.html
上代码
代码(参考调用)
taskService.convertListToMap(taskList,BoardTask::getType);
方法
//传入一个list<T>,返回一个指定key的list<T>的map
public static <T> Map<String, List<T>> convertListToMap(List<T> list, Function<T, String> keyExtractor) {
return list.stream()
.collect(Collectors.groupingBy(keyExtractor));
}
到了这里,关于Java将一个list<T>指定key转换成Map<list>的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!