当前位置:网站首页>Using stream API instead of SQL
Using stream API instead of SQL
2022-06-22 17:53:00 【Stay for love】
hypothesis mysql There are two tables in the database :
user User table

company Enterprise table

When the above two types of data are not stored in the database , They come from two interfaces , If you want to do something about the data from two different interfaces join,group(sum),order,limit Wait for the operation , We need to use it stream api To process
stay java of use list To encapsulate the user , Enterprise information :
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
use mysql Realization :
SELECT * FROM user order by age DESC; 
use stream api(sorted) Realization :
static List<User> processOrder(List<User> userList){
return userList.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());
}
limit
use mysql Realization :
SELECT * FROM user order by age DESC limit 2;
use stream api(limit) Realization :
static List<User> processOrderLimit(List<User> userList){
return userList.stream().sorted(Comparator.comparing(User::getAge).reversed()).limit(2).collect(Collectors.toList());
}
limt Pagination
use mysql Realization :
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;among limit offset,length among offset= (pageIndex-1)*pageSize ,length=pageSize
use stream api(skip,limit) Realization :
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
use sql Realization :
SELECT SUM(age) num,type FROM user GROUP BY type ORDER BY num DESC;
use stream api(groupingBy,sorted) Realization :
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));
}use stream api(merge,sorted) Realization :
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
use mysql Realization :
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;use stream api Realization :
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();
}
}
}边栏推荐
- Development mode of JSP learning
- 诺亚财富拟登陆港交所:第一季度业绩大幅下滑,曾踩雷“承兴案”
- STM32系列(HAL库)——F103C8T6硬件SPI点亮带字库OLED屏
- 【FPGA+PWM】基于FPGA的三相PWM整流器移相触发电路的设计与实现
- Short video live broadcast source code, use of EditText input box
- 来厦门了!线上交流限额免费报名中
- [mysql] data synchronization prompt: specified key was too long; max key length is 767 bytes
- [mysql] install multiple MySQL versions on one Windows computer
- Content recommendation process
- 无心剑中文随感《探求真谛》
猜你喜欢

Qt筆記-QMap自定義鍵(key)

Kibana+elk cluster log processing

Hello Playwright:(7)模拟键盘和鼠标

缺失值處理

如何做好研发效能度量及指标选取

MySQL master-slave connection prompt of docker: communications link failure

WPF效果第一百九十篇之再耍ListBox

Ad20/altium Designer - oil for manhole cover

Gridhome, a must-have static site generator for beginners

math_角函数&反三角函数
随机推荐
Xshell 7(SSH远程终端工具) v7.0.0109 官方中文正式版(附文件+安装教程)
同花顺软件是什么?手机开户安全么?
STM32 series (HAL Library) - f103c8t6 hardware SPI illuminates OLED screen with word library
【进阶自动化测试第一步】1分钟带你了解自动化测试
Seeing the big from the small: a simple example of domain modeling, understanding "domain driven".
What is flush software? Is it safe to open a mobile account?
Quartus prime 18.0 software installation package and installation tutorial
Blazor University (31)表单 —— 验证
A new mode of enterprise software development: low code
Cloud minimalist deployment svelte3 chat room
Cross platform brake browser
MySQL instruction executes SQL file
Gridhome, a must-have static site generator for beginners
Review the executor from the perspective of application submission
Apache ShardingSphere 一文读懂
同花顺软件是什么?网上开户安全么?
DAP事实表加工汇总功能应用说明
Xftp 7(FTP/SFTP客户端) V7.0.0107 官方中文免费正式版(附文件+安装教程)
Recommend 7 super easy-to-use terminal tools - ssh+ftp
WPF效果第一百九十篇之再耍ListBox