diff --git a/java/core/src/main/java/com/google/protobuf/DynamicMessage.java b/java/core/src/main/java/com/google/protobuf/DynamicMessage.java
index f25aa23e7302f..f518284147ead 100644
--- a/java/core/src/main/java/com/google/protobuf/DynamicMessage.java
+++ b/java/core/src/main/java/com/google/protobuf/DynamicMessage.java
@@ -15,8 +15,10 @@
import com.google.protobuf.Descriptors.OneofDescriptor;
import java.io.IOException;
import java.io.InputStream;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -415,6 +417,8 @@ public DynamicMessage buildPartial() {
}
}
+ normalizeMapFields();
+
DynamicMessage result =
new DynamicMessage(
type,
@@ -424,6 +428,56 @@ public DynamicMessage buildPartial() {
return result;
}
+
+ /**
+ * Collapses duplicate keys within map fields, keeping the last value seen.
+ *
+ *
The language guide requires that when a map is parsed from the wire and the same key
+ * appears more than once, the last value wins. Generated messages get this for free because
+ * they store map fields in a {@code MapField}, but {@code DynamicMessage} keeps them in a
+ * {@code FieldSet} as a plain list of {@code MapEntry} messages that is appended to
+ * unconditionally, so duplicate keys survived a parse. That made {@code DynamicMessage} and a
+ * generated message produce different results, and different serializations, for identical and
+ * well-formed wire input.
+ *
+ *
Normalizing once here rather than on every {@code addRepeatedField} keeps parsing linear;
+ * de-duplicating at insertion time would make parsing an n-entry map O(n^2).
+ */
+ private void normalizeMapFields() {
+ int numFields = type.getFieldCount();
+ for (int i = 0; i < numFields; i++) {
+ FieldDescriptor field = type.getField(i);
+ if (!field.isMapField()) {
+ continue;
+ }
+ // Map fields are repeated, so hasField() does not apply; getField() returns null when the
+ // field was never populated.
+ Object fieldValue = fields.getField(field);
+ if (!(fieldValue instanceof List)) {
+ continue;
+ }
+ List> entries = (List>) fieldValue;
+ if (entries.size() < 2) {
+ continue;
+ }
+ FieldDescriptor keyField = field.getMessageType().findFieldByNumber(1);
+ if (keyField == null) {
+ continue;
+ }
+ Map