当前位置:网站首页>如何优雅的获取每个分组的前几条数据
如何优雅的获取每个分组的前几条数据
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()))));
总结
第二种方式中查询的数据有点大,建议还是用第一种好点。
边栏推荐
- 企业级:Spire.Office for .NET:Platinum|7.7.x
- ClickPaaS低代码平台
- Number of possible stack order types of stack order with length n
- 小程序中实现文章的关注功能
- Technical tutorial: how to use easydss to push live streaming to qiniu cloud?
- Rust blockchain development - signature encryption and private key public key
- 陇原战“疫“2021网络安全大赛 Web EasyJaba
- Alibaba cloud ECS uses cloudfs4oss to mount OSS
- Judge whether the stack order is reasonable according to the stack order
- Threejs factory model 3DMAX model obj+mtl format, source file download
猜你喜欢

【刷题】BFS题目精选

mysql的七种join连接查询
![[数组]566. 重塑矩阵-简单](/img/3c/593156f5bde67bd56828106d7bed3c.png)
[数组]566. 重塑矩阵-简单

Pyqt pyside custom telescopic menu bar sharing (including tutorial)
![[wp][introduction] brush weak type questions](/img/d0/9eb3ade701057837d98e4a20082a10.png)
[wp][introduction] brush weak type questions

Uni app change the default component style

Uni app common functions /api

Pyqt5 displays file names and pictures

【UNIAPP】系统热更新实现思路

UI自动化测试从此告别手动下载浏览器驱动
随机推荐
Summary of scene design
FFmepg使用指南
特殊版:SpreadJS v15.1 VS SpreadJS v15.0
NEW:Devart dotConnect ADO.NET
BDF application - topology sequence
Rome链分析
Threejs loads the city obj model, loads the character gltf model, and tweetjs realizes the movement of characters according to the planned route
Threejs rendering obj+mtl model source code, 3D factory model
ActiveReportsJS 3.1 VS ActiveReportsJS 3.0
Is there a sudden failure on the line? How to make emergency diagnosis, troubleshooting and recovery
IronXL for .NET 2022.6
Looking back on 2021, looking forward to 2022 | a year between CSDN and me
A application wakes up B should be a fast method
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
长度为n的入栈顺序的可能出栈顺序种数
laravel8 导出Excle文件
The order of LDS links
【UNIAPP】系统热更新实现思路
Alibaba cloud ECS uses cloudfs4oss to mount OSS
Rust blockchain development - signature encryption and private key public key