diff --git a/src/main/java/org/apache/commons/csv/CSVRecord.java b/src/main/java/org/apache/commons/csv/CSVRecord.java index 5524d9e8..0e70ad75 100644 --- a/src/main/java/org/apache/commons/csv/CSVRecord.java +++ b/src/main/java/org/apache/commons/csv/CSVRecord.java @@ -88,7 +88,7 @@ public final class CSVRecord implements Serializable, Iterable { } /** - * Returns a value by name. + * Returns a value by name. If multiple instances of the header name exists, only the last occurence is returned. * *

* Note: This requires a field mapping obtained from the original parser. @@ -311,7 +311,9 @@ public final class CSVRecord implements Serializable, Iterable { } /** - * Copies this record into a new Map of header name to record value. + * Copies this record into a new Map of header name to record value. If multiple instances of a header name exists, + * only the last occurence is mapped. + * *

* Editing the map does not update this instance. *

diff --git a/src/test/java/org/apache/commons/csv/CSVRecordTest.java b/src/test/java/org/apache/commons/csv/CSVRecordTest.java index 4833c26c..db1ef40c 100644 --- a/src/test/java/org/apache/commons/csv/CSVRecordTest.java +++ b/src/test/java/org/apache/commons/csv/CSVRecordTest.java @@ -23,6 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertAll; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -341,6 +342,37 @@ public class CSVRecordTest { assertTrue(recordWithHeader.toString().contains("values=")); } + @Test + public void testDuplicateHeaderGet() throws IOException { + final String csv = "A,A,B,B\n1,2,5,6\n"; + final CSVFormat format = CSVFormat.DEFAULT.builder().setHeader().build(); + + try (final CSVParser parser = CSVParser.parse(csv, format)) { + final CSVRecord record = parser.nextRecord(); + + assertAll("Test that it gets the last instance of a column when there are duplicate headings", + () -> assertEquals("2", record.get("A")), + () -> assertEquals("6", record.get("B")) + ); + } + } + + @Test + public void testDuplicateHeaderToMap() throws IOException { + final String csv = "A,A,B,B\n1,2,5,6\n"; + final CSVFormat format = CSVFormat.DEFAULT.builder().setHeader().build(); + + try (final CSVParser parser = CSVParser.parse(csv, format)) { + final CSVRecord record = parser.nextRecord(); + final Map map = record.toMap(); + + assertAll("Test that it gets the last instance of a column when there are duplicate headings", + () -> assertEquals("2", map.get("A")), + () -> assertEquals("6", map.get("B")) + ); + } + } + private void validateMap(final Map map, final boolean allowsNulls) { assertTrue(map.containsKey(EnumHeader.FIRST.name())); assertTrue(map.containsKey(EnumHeader.SECOND.name()));