使用map优化双层for循环

文章目录


前言

比如我们现在拿到两个list 数据 ,一个是 User List 集合 ;另一个是 UserMemo List集合;

java 复制代码
@Data
public class User {
    private Long userId;
    private String name;
}
代码 UserMemo.java :
@Data
public class UserMemo {
    private Long userId;
    private String content;
}
java 复制代码
public static List<User> getUserTestList() {
        List<User> users = new ArrayList<>();
        for (int i = 1; i <= 50000; i++) {
            User user = new User();
            user.setName(UUID.randomUUID().toString());
            user.setUserId((long) i);
            users.add(user);
        }
        return users;
    }
    public static List<UserMemo> getUserMemoTestList() {
        List<UserMemo> userMemos = new ArrayList<>();
        for (int i = 30000; i >= 1; i--) {
            UserMemo userMemo = new UserMemo();
            userMemo.setContent(UUID.randomUUID().toString());
            userMemo.setUserId((long) i);
            userMemos.add(userMemo);
        }
        return userMemos;
    }

我们需要遍历 User List ,然后根据 userId 从 UserMemo List 里面取出 对应这个userId 的 content 值,做数据处理。

就是 for循环 里面还有 for循环, 然后做一些数据匹配、处理 这种场景。

java 复制代码
for (User user : userTestList) {
    Long userId = user.getUserId();
    for (UserMemo userMemo : userMemoTestList) {
        if (userId.equals(userMemo.getUserId())) {
            String content = userMemo.getContent();
            System.out.println("模拟数据content 业务处理......"+content);
        }
    }
}

注意:只考虑每个userId 在 UserMemo List 里面 都是只有一条数据的场景。


优化双层for循环

java 复制代码
public static void main(String[] args) {
        List<User> userTestList = getUserTestList();
        List<UserMemo> userMemoTestList = getUserMemoTestList();
        //直观的输出代码执行耗时,以及执行时间百分比
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        //关键步骤,将list转换为map
        Map<Long, String> contentMap =
                userMemoTestList.stream().filter(e->e.getUserId != null).collect(Collectors.toMap(UserMemo::getUserId, UserMemo::getContent));
        for (User user : userTestList) {
            Long userId = user.getUserId();
            String content = contentMap.get(userId);
            if (StringUtils.hasLength(content)) {
                System.out.println("模拟数据content 业务处理......" + content);
            }
        }
        stopWatch.stop();
        System.out.println("最终耗时" + stopWatch.getTotalTimeMillis());
    }

map的取值效率 在多数的情况下是能维持接近 O(1) 的 , 毕竟数据结构摆着,数组加链表。


相关推荐
ok!ko23 分钟前
设计模式之原型模式(通俗易懂--代码辅助理解【Java版】)
java·设计模式·原型模式
代码雕刻家1 小时前
数据结构-3.9.栈在递归中的应用
c语言·数据结构·算法
2402_857589361 小时前
“衣依”服装销售平台:Spring Boot框架的设计与实现
java·spring boot·后端
吾爱星辰1 小时前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin
ChinaDragonDreamer1 小时前
Kotlin:2.0.20 的新特性
android·开发语言·kotlin
IT良1 小时前
c#增删改查 (数据操作的基础)
开发语言·c#
哎呦没2 小时前
大学生就业招聘:Spring Boot系统的架构分析
java·spring boot·后端
Kalika0-02 小时前
猴子吃桃-C语言
c语言·开发语言·数据结构·算法
_.Switch2 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
编程、小哥哥2 小时前
netty之Netty与SpringBoot整合
java·spring boot·spring