Skip to content

Commit 12386c8

Browse files
authored
Skip UseMapOf for LinkedHashMap/TreeMap in prose put-statement form (#1163) (#1165)
1 parent ee2f4c4 commit 12386c8

2 files changed

Lines changed: 30 additions & 0 deletions

File tree

src/main/java/org/openrewrite/java/migrate/util/UseMapOf.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,12 @@ private String matchingTargetName(J.VariableDeclarations decl) {
302302
if (!NEW_HASH_MAP.matches(nc)) {
303303
return null;
304304
}
305+
// Skip `HashMap` subclasses like `LinkedHashMap`/`TreeMap`: `Map.of(..)` makes no
306+
// iteration-order guarantee, so absorbing their `put(..)` chain would silently drop
307+
// the ordering contract the original code relied on (issue #1163, matching #1113).
308+
if (!TypeUtils.isOfClassType(nc.getClazz() != null ? nc.getClazz().getType() : null, "java.util.HashMap")) {
309+
return null;
310+
}
305311
if (nc.getBody() != null) {
306312
return null;
307313
}

src/test/java/org/openrewrite/java/migrate/util/UseMapOfTest.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,30 @@ class Test {
290290
);
291291
}
292292

293+
@Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/1163")
294+
@Test
295+
void doNotChangeLinkedHashMapBuiltWithPutStatements() {
296+
//language=java
297+
rewriteRun(
298+
java(
299+
"""
300+
import java.util.LinkedHashMap;
301+
import java.util.Map;
302+
303+
class Test {
304+
static Map<String, String> ordered() {
305+
Map<String, String> m = new LinkedHashMap<>();
306+
m.put("a", "1");
307+
m.put("b", "2");
308+
m.put("c", "3");
309+
return m;
310+
}
311+
}
312+
"""
313+
)
314+
);
315+
}
316+
293317
@Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/566")
294318
@Test
295319
void changeDoubleBraceInitForNonStringTypes() {

0 commit comments

Comments
 (0)