当前位置:网站首页>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();
        }
    }
}

原网站

版权声明
本文为[Stay for love]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221507398708.html