当前位置:网站首页>How to get the first few pieces of data of each group gracefully

How to get the first few pieces of data of each group gracefully

2022-07-05 04:12:00 Peipei Dad

background

Recently, when changing a function , Find out that there is a need to get the answer to each question 3 The best reply content of .

And then combine it into list. Return to the front end .

You may think this is relatively simple , Find all of them , Then one for loop , It's done .

But as an ideal , Pretending programmer , How can we do such an operation ?

Solution

One 、 Use mysql solve

This scheme is quite common online .

SQL Put on

select media_id from article a
where  3>=(select count(1) from article where `status`=1 and media_id=a.media_id and hot_num > a.hot_num)
 order by a.media_id,id desc;

Two 、 Use stream Of groupBy solve

Map<String, List<Article>> map = list.stream()
                .collect(Collectors.groupingBy(Article::getMediaId,
                        Collectors.collectingAndThen(Collectors.toList(),
                                list2 -> list2.stream().sorted(Comparator.comparing(Article::getHdNum, Comparator.reverseOrder())).limit(3).collect(Collectors.toList()))));

 

summary

The data queried in the second method is a little large , It is better to use the first one .

原网站

版权声明
本文为[Peipei Dad]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050406490290.html