经常有这种,一个数据库里有多个字段,但是数据库只能返回一个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<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));
}