我有一个List并需要将其转换为嵌套(2级)地图,其中list由2个不同的对象属性分组,值应使用第三个属性。例如:
[A("1","2","3"),A("1","2","4"),A("1","3","4"),A("2","3","5")]
应转换为
{1={2=[3, 4], 3=[4]}, 2={3=[5]}}
现在得到这个结果我使用以下结构:
Map<String,Map<String,List<A>>> grouppedRecords = list.stream().collect(groupingBy(A::getA, groupingBy(A::getB)));
Map<String,Map<String,List<String>>> results = grouppedRecords.entrySet().stream().collect(Collectors.toMap(
Map.Entry::getKey,
e12 -> e12.getValue().entrySet().stream().collect(Collectors.toMap(
Map.Entry::getKey,
e22 -> e22.getValue().stream().map(A::getC).collect(Collectors.toList())
)))
);
但它看起来过于复杂。你能帮助我更好地解决同样的问题吗?
答案 0 :(得分:3)
您可以使用const Post = require('../models/post');
const Comment = require('../models/comment');
getpost: async (req, res, next) => {
const { post_id } = req.params;
const post = await Post.findById(post_id);
const comments_id = post._comment;
var comments = [];
comments_id.forEach(async id => {
comments.push(await Comment.findById(id));
console.log(comments) // The output are elements which exist in Comment model
});
console.log(comments); // The output is []
comments.forEach(comment => {
console.log(comment);
});
将Collectors.mapping
个实例映射到A
:
getC()