当前位置:网站首页>如何优雅的获取每个分组的前几条数据
如何优雅的获取每个分组的前几条数据
2022-07-05 04:06:00 【沛沛老爹】
背景
最近在改一个功能时,发现有个需要获取每个问题回答的前3条的最优回复内容。
然后组合成list。返回给到前端。
大家可能觉得这个比较简单,找出所有的来,然后一个for循环,解决完事。
但是作为有理想的,装逼的程序员,我们怎么能做这样的操作?
解决方案
一、使用mysql解决
这个方案网上比较常见。
SQL贴上
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;
二、使用stream的groupBy解决
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()))));
总结
第二种方式中查询的数据有点大,建议还是用第一种好点。
边栏推荐
- Common features of ES6
- Uni app change the default component style
- Use object composition in preference to class inheritance
- Clickhouse materialized view
- 陇原战“疫“2021网络安全大赛 Web EasyJaba
- 企业级:Spire.Office for .NET:Platinum|7.7.x
- About the recent experience of writing questions
- How to solve the problem that easycvr changes the recording storage path and does not generate recording files?
- Use threejs to create geometry, dynamically add geometry, delete geometry, and add coordinate axes
- Longyuan war "epidemic" 2021 network security competition web easyjaba
猜你喜欢
About the project error reporting solution of mpaas Pb access mode adapting to 64 bit CPU architecture
On the day 25K joined Tencent, I cried
Threejs Internet of things, 3D visualization of farms (I)
【虚幻引擎UE】运行和启动的区别,常见问题分析
Rust blockchain development - signature encryption and private key public key
Enterprise level: spire Office for . NET:Platinum|7.7. x
Behavior perception system
在线文本行固定长度填充工具
This article takes you to understand the relationship between the past and present of Bi and the digital transformation of enterprises
快手、抖音、视频号交战内容付费
随机推荐
Threejs Internet of things, 3D visualization of farm (III) model display, track controller setting, model moving along the route, model adding frame, custom style display label, click the model to obt
Learning notes 8
Open graph protocol
输入的查询SQL语句,是如何执行的?
Phpmailer reported an error: SMTP error: failed to connect to server: (0)
FFmepg使用指南
Use Firefox browser to quickly pick up Web image materials
@The problem of cross database query invalidation caused by transactional annotation
Scheduling system of kubernetes cluster
Clickhouse synchronization MySQL (based on materialization engine)
Three level linkage demo of uniapp uview u-picker components
[wp][introduction] brush weak type questions
UI automation test farewell to manual download of browser driver
Pyqt5 displays file names and pictures
25K 入职腾讯的那天,我特么哭了
北京程序员的真实一天!!!!!
Longyuan war "epidemic" 2021 network security competition web easyjaba
UI自动化测试从此告别手动下载浏览器驱动
在线文本行固定长度填充工具
我就一写代码的,王总整天和我谈格局...