当前位置:网站首页>如何优雅的获取每个分组的前几条数据
如何优雅的获取每个分组的前几条数据
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()))));
总结
第二种方式中查询的数据有点大,建议还是用第一种好点。
边栏推荐
- [brush questions] BFS topic selection
- A application wakes up B should be a fast method
- Threejs factory model 3DMAX model obj+mtl format, source file download
- Pyqt pyside custom telescopic menu bar sharing (including tutorial)
- 技术教程:如何利用EasyDSS将直播流推到七牛云?
- Scheduling system of kubernetes cluster
- [wp]bmzclub writeup of several questions
- Alibaba cloud ECS uses cloudfs4oss to mount OSS
- ActiveReportsJS 3.1 VS ActiveReportsJS 3.0
- [understand series after reading] 6000 words teach you to realize interface automation from 0 to 1
猜你喜欢
Seven join join queries of MySQL
Containerd series - detailed explanation of plugins
我就一写代码的,王总整天和我谈格局...
如何实现实时音视频聊天功能
在线文本行固定长度填充工具
行为感知系统
为什么百度、阿里这些大厂宁愿花25K招聘应届生,也不愿涨薪5K留住老员工?
Threejs factory model 3DMAX model obj+mtl format, source file download
Alibaba cloud ECS uses cloudfs4oss to mount OSS
3. Package the bottom navigation tabbar
随机推荐
3. Package the bottom navigation tabbar
我国算力规模排名全球第二:计算正向智算跨越
open graph协议
[untitled]
ActiveReportsJS 3.1 VS ActiveReportsJS 3.0
10种寻址方式之间的区别
如何实现实时音视频聊天功能
优先使用对象组合,而不是类继承
Deep learning - LSTM Foundation
web资源部署后navigator获取不到mediaDevices实例的解决方案(navigator.mediaDevices为undefined)
Threejs Internet of things, 3D visualization of farms (I)
ActiveReportsJS 3.1 VS ActiveReportsJS 3.0
error Couldn‘t find a package. JSON file in "your path“
Threejs loads the city obj model, loads the character gltf model, and tweetjs realizes the movement of characters according to the planned route
面试汇总:这是一份全面&详细的Android面试指南
北京程序员的真实一天!!!!!
根据入栈顺序判断出栈顺序是否合理
Test d'automatisation de l'interface utilisateur télécharger manuellement le pilote du navigateur à partir de maintenant
Bit operation skills
网络安全-记录web漏洞修复