How to Speed Up Nested Loops in Java: Break and Map Tricks
This article walks through a common Java scenario of matching two large lists with nested loops, measures the poor performance, then demonstrates two optimizations—adding a break statement and replacing the inner loop with a HashMap—to dramatically cut execution time.
The problem is to match userId from a User list with the corresponding content in a UserMemo list, which many developers implement with two nested for loops.
Naïve code iterates 50,000 users against 30,000 memos (150 million comparisons), taking about 26,857 ms on the test data.
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);
}
}
}**Optimization 1 – break early**: when each userId appears only once in UserMemo, the inner loop can stop after the first match. Adding break reduces the runtime to roughly 10 seconds.
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);
break;
}
}
}**Optimization 2 – use a HashMap **: build a map from userId to content once, then look up each user in O(1) time, changing the overall complexity from O(N·M) to O(N+M).
Map<Long, String> contentMap = userMemoTestList.stream()
.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);
}
}Running this version on the same 50 k / 30 k data set drops the total time to a few seconds (the screenshot shows about 2 000 ms), because hash‑based lookups are near‑constant time; JDK 8’s hash function distributes keys uniformly, making collisions rare. Even in the worst case where all keys collide, the cost would be O(n), which is still far better than the original O(N·M) nested loops.
Java Web Project
Focused on Java backend technologies, trending internet tech, and the latest industry developments. The platform serves over 200,000 Java developers, inviting you to learn and exchange ideas together. Check the menu for Java learning resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
