IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 大数据 -> 使用stream api替代sql -> 正文阅读

[大数据]使用stream api替代sql

假设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();
        }
    }
}

  大数据 最新文章
实现Kafka至少消费一次
亚马逊云科技:还在苦于ETL?Zero ETL的时代
初探MapReduce
【SpringBoot框架篇】32.基于注解+redis实现
Elasticsearch:如何减少 Elasticsearch 集
Go redis操作
Redis面试题
专题五 Redis高并发场景
基于GBase8s和Calcite的多数据源查询
Redis——底层数据结构原理
上一篇文章      下一篇文章      查看所有文章
加:2022-06-18 23:28:02  更:2022-06-18 23:28:04 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 16:29:52-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码