当前位置:网站首页>如何优雅的获取每个分组的前几条数据
如何优雅的获取每个分组的前几条数据
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()))));
总结
第二种方式中查询的数据有点大,建议还是用第一种好点。
边栏推荐
- How to use jedis of redis
- Deflocculant aminoiodotide eye drops
- JVM garbage collection
- Online sql to excel (xls/xlsx) tool
- EasyCVR平台出现WebRTC协议视频播放不了是什么原因?
- ActiveReportsJS 3.1 VS ActiveReportsJS 3.0
- The scale of computing power in China ranks second in the world: computing is leaping forward in Intelligent Computing
- Threejs rendering obj+mtl model source code, 3D factory model
- How to realize real-time audio and video chat function
- FFmepg使用指南
猜你喜欢

As soon as I write the code, President Wang talks with me about the pattern all day

【虚幻引擎UE】实现UE5像素流部署仅需六步操作少走弯路!(4.26和4.27原理类似)

Soul 3: what is interface testing, how to play interface testing, and how to play interface automation testing?

为什么百度、阿里这些大厂宁愿花25K招聘应届生,也不愿涨薪5K留住老员工?

Is "golden nine and silver ten" the best time to find a job? Not necessarily

NEW:Devart dotConnect ADO. NET

Threejs implements labels and displays labels with custom styles

Test d'automatisation de l'interface utilisateur télécharger manuellement le pilote du navigateur à partir de maintenant

How to solve the problem that easycvr changes the recording storage path and does not generate recording files?

An elegant program for Euclid‘s algorithm
随机推荐
error Couldn‘t find a package. JSON file in "your path“
DFS and BFS concepts of trees and graphs
JVM garbage collection
技术教程:如何利用EasyDSS将直播流推到七牛云?
特殊版:SpreadJS v15.1 VS SpreadJS v15.0
Common features of ES6
灵魂三问:什么是接口测试,接口测试怎么玩,接口自动化测试怎么玩?
【虚幻引擎UE】打包报错出现!FindPin错误的解决办法
Online text line fixed length fill tool
NEW:Devart dotConnect ADO. NET
Threejs realizes sky box, panoramic scene, ground grass
provide/inject
Three level linkage demo of uniapp uview u-picker components
10种寻址方式之间的区别
长度为n的入栈顺序的可能出栈顺序种数
How does the applet solve the rendering layer network layer error?
[Chongqing Guangdong education] 2408t Chinese contemporary literature reference test in autumn 2018 of the National Open University
As soon as I write the code, President Wang talks with me about the pattern all day
[wp]bmzclub writeup of several questions
Seven join join queries of MySQL