当前位置:网站首页>使用stream api替代sql
使用stream api替代sql
2022-06-22 15:08:00 【为爱停留】
假设mysql数据库中有两张表:
user用户表

company企业表

当这以上两种类型的数据不是存放在数据库中,而是分别来自两个接口,如果想要对分别来自两个不同的接口的数据做一些join,group(sum),order,limit等操作的时候,我们就需要使用stream api来进行处理
在java中用list来封装用户,企业信息:
static List<User> buildUserList(){
ArrayList list = new ArrayList();
list.add(new User(1,"yc",31,2));
list.add(new User(2,"yf",32,2));
list.add(new User(3,"yy",29,1));
list.add(new User(4,"yl",26,1));
list.add(new User(5,"ygf",27,3));
return list;
}
static List<Company> buildCompanyList(){
ArrayList list = new ArrayList();
list.add(new Company(1,1,"H001","WN"));
list.add(new Company(2,2,"H001","WN"));
list.add(new Company(3,3,"H002","CXY"));
return list;
}@Data
public class Company {
private Integer id;
private Integer userId;
private String code;
private String name;
public Company(Integer id, Integer userId, String code, String name) {
this.id = id;
this.userId = userId;
this.code = code;
this.name = name;
}
}
@Data
public class User {
private Integer id;
private String name;
private Integer age;
private Integer type;
public User(Integer id, String name, Integer age, Integer type) {
this.id = id;
this.name = name;
this.age = age;
this.type = type;
}
}
order
用mysql实现:
SELECT * FROM user order by age DESC; 
用stream api(sorted)实现:
static List<User> processOrder(List<User> userList){
return userList.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());
}
limit
用mysql实现:
SELECT * FROM user order by age DESC limit 2;
用stream api(limit)实现:
static List<User> processOrderLimit(List<User> userList){
return userList.stream().sorted(Comparator.comparing(User::getAge).reversed()).limit(2).collect(Collectors.toList());
}
limt分页
用mysql实现:
SELECT * FROM user order by age DESC limit 0,2;
SELECT * FROM user order by age DESC limit 2,2;
SELECT * FROM user order by age DESC limit 4,2;其中limit offset,length其中 offset= (pageIndex-1)*pageSize ,length=pageSize
用stream api(skip,limit)实现:
List<User> userList = processOrderLimitPage(buildUserList(),1,2);
List<User> userList = processOrderLimitPage(buildUserList(),2,2);
List<User> userList = processOrderLimitPage(buildUserList(),3,2); static List<User> processOrderLimitPage(List<User> userList,Integer pageIndex,Integer pageSize){
return userList.stream().sorted(Comparator.comparing(User::getAge).reversed()).skip((pageIndex-1)*pageSize).limit(pageSize).collect(Collectors.toList());
}group(sum),order
用sql实现:
SELECT SUM(age) num,type FROM user GROUP BY type ORDER BY num DESC;
用stream api(groupingBy,sorted)实现:
static Map<Integer,Integer> processGroupSum(List<User> userList){
return userList.stream().collect(Collectors.groupingBy(User::getType,Collectors.summingInt(User::getAge))).entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(oldVal, newVal) -> oldVal,
LinkedHashMap::new));
}用stream api(merge,sorted)实现:
static Map<Integer,Integer> processMergeSum(List<User> userList){
Map<Integer,Integer> map = new HashMap<>();
userList.stream().forEach(x->map.merge(x.getType(),x.getAge(),Integer::sum));
return map.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(oldVal, newVal) -> oldVal,
LinkedHashMap::new));
}
inner join,left join,right join
用mysql实现:
select * from `user` INNER JOIN company ON `user`.id = company.user_id;
select * from `user` left JOIN company ON `user`.id = company.user_id;
select * from `user` right JOIN company ON `user`.id = company.user_id;用stream api实现:
List<UserCompany> userCompanyList = processJoin(buildUserList(),buildCompanyList(),"inner");
List<UserCompany> userCompanyList = processJoin(buildUserList(),buildCompanyList(),"left");
List<UserCompany> userCompanyList = processJoin(buildUserList(),buildCompanyList(),"right"); static List<UserCompany> processJoin(List<User> userList, List<Company> companyList,String type) {
Map<Integer, List<User>> userMap = userList.stream().collect(Collectors.groupingBy(User::getId));
Map<Integer, List<Company>> companyMap = companyList.stream().collect(Collectors.groupingBy(Company::getUserId));
Set<Integer> integerList = new HashSet<>();
if("join".equals(type)){
integerList = userMap.keySet().stream().filter(companyMap.keySet()::contains).collect(Collectors.toSet());
Set<Integer> finalIntegerList = integerList;
userMap = userMap.entrySet().stream().filter(x -> finalIntegerList.contains(x.getKey())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
companyMap = companyMap.entrySet().stream().filter(x -> finalIntegerList.contains(x.getKey())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
if("left".equals(type)){
integerList = userMap.keySet();
}else if("right".equals(type)){
integerList = companyMap.keySet();
}
List<UserCompany> userCompanyList = new ArrayList<>();
Map<Integer, List<User>> finalUserMap = userMap;
Map<Integer, List<Company>> finalCompanyMap = companyMap;
integerList.forEach(x -> {
List<User> userList1 = finalUserMap.get(x);
List<Company> companyList1 = finalCompanyMap.get(x);
userList1.forEach(m -> {
if(!CollectionUtils.isEmpty(companyList1)) {
companyList1.forEach(n -> {
userCompanyList.add(new UserCompany(m, n));
});
}else{
userCompanyList.add(new UserCompany(m,null));
}
});
});
return userCompanyList;
}@Data
public class UserCompany {
private Integer userId;
private String name;
private Integer age;
private Integer type;
private Integer companyId;
private String code;
private String companyName;
public UserCompany(User user,Company company) {
if(user != null){
this.userId = user.getId();
this.name = user.getName();
this.age = user.getAge();
this.type = user.getType();
}
if(company != null){
this.companyId = company.getId();
this.code = company.getCode();
this.companyName = company.getCode();
}
}
}边栏推荐
- ironSource Luna 推出苹果搜索广告限时优惠,注册即享3个月免费服务
- Gbase "library" special training of innovation and application Committee of Beijing fintech Industry Alliance
- 解决mysql远程登录报权限问题
- LeetCode_回溯_动态规划_中等_131.分割回文串
- Pod type
- '不敢去怀疑代码,又不得不怀疑代码'记一次网络请求超时分析
- [single chip microcomputer] [make buzzer sound] know the buzzer and let it make the sound you want
- Make the text template in pycharm project support jinjia2 syntax
- 3.抽象類(shape)
- The odoo system sets priorities for the views independently developed by the original model
猜你喜欢

Runtime——探索类,对象,分类本质

让pycharm项目里面的文本模板支持jinjia2语法

Cve-2022-0847 (privilege lifting kernel vulnerability)

6.GUI(图形,填充)

信创研究:国产数据库聚焦信创市场,华为Gauss有望成为最强
![[Shanda conference] application setting module](/img/1e/1665234715b365614a753355274ced.png)
[Shanda conference] application setting module

Navicat Premium 连接Oracle 数据库(图文教程)

odoo本地文档功能开发记录

84. (cesium chapter) movement of cesium model on terrain

数睿数据荣获第二届ISIG中国产业智能大会两项年度大奖
随机推荐
Jenkins automatically triggers compilation by checking code submissions
5. reading and writing of documents (students)
2.接口(计算器)
【LeetCode】9、回文数
6.GUI(图形,填充)
nvarchar和varchar的区别
Differences between Oracle client and server
B树和B+树
pymssql模块使用指南
Oracle客户端和服务端的区别
3.抽象類(shape)
Process address space
[Shanda conference] private chat channel webrtc tools
Quick sort_ sort
SAP ABAP 中的用户出口和客户出口-015
SAP 中的 ABAP 查询教程:SQ01、SQ02、SQ03-017
stack和queue的模拟实现
在JFlash中添加未知类型的单片机
Default function control =default and =delete
School enterprise alliance is on the way! Huawei cloud gaussdb has come to universities again