当前位置:网站首页>如何优雅的获取每个分组的前几条数据
如何优雅的获取每个分组的前几条数据
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()))));
总结
第二种方式中查询的数据有点大,建议还是用第一种好点。
边栏推荐
- Wechat applet development process (with mind map)
- IronXL for .NET 2022.6
- The development of mobile IM based on TCP still needs to keep the heartbeat alive
- Clickhouse materialized view
- 在线文本行固定长度填充工具
- open graph协议
- Why can't all browsers on my computer open web pages
- Threejs Internet of things, 3D visualization of factory
- Possible stack order of stack order with length n
- Threejs loads the city obj model, loads the character gltf model, and tweetjs realizes the movement of characters according to the planned route
猜你喜欢
随机推荐
provide/inject
Judge whether the stack order is reasonable according to the stack order
【虚幻引擎UE】实现测绘三脚架展开动画制作
Phpmailer reported an error: SMTP error: failed to connect to server: (0)
北京程序员的真实一天!!!!!
线上故障突突突?如何紧急诊断、排查与恢复
This article takes you to understand the relationship between the past and present of Bi and the digital transformation of enterprises
Rome链分析
10种寻址方式之间的区别
EasyCVR平台出现WebRTC协议视频播放不了是什么原因?
C language course setting: cinema ticket selling management system
MindFusion. Virtual Keyboard for WPF
[Chongqing Guangdong education] 2408t Chinese contemporary literature reference test in autumn 2018 of the National Open University
官宣!第三届云原生编程挑战赛正式启动!
Learning notes 8
我国算力规模排名全球第二:计算正向智算跨越
反絮凝剂-氨碘肽滴眼液
Enterprise level: spire Office for . NET:Platinum|7.7. x
Study notes 7
C语言课设:影院售票管理系统







![[数组]566. 重塑矩阵-简单](/img/3c/593156f5bde67bd56828106d7bed3c.png)

