Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/main/java/org/apache/commons/csv/CSVRecord.java
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public String get(final int i) {
}

/**
* Returns a value by name.
* Returns a value by name. If multiple instances of the header name exists, only the last occurence is returned.
*
* <p>
* Note: This requires a field mapping obtained from the original parser.
Expand Down Expand Up @@ -311,7 +311,9 @@ public List<String> toList() {
}

/**
* 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.
*
* <p>
* Editing the map does not update this instance.
* </p>
Expand Down
32 changes: 32 additions & 0 deletions src/test/java/org/apache/commons/csv/CSVRecordTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
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;
Expand Down Expand Up @@ -341,6 +342,37 @@ public void testToString() {
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<String, String> 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<String, String> map, final boolean allowsNulls) {
assertTrue(map.containsKey(EnumHeader.FIRST.name()));
assertTrue(map.containsKey(EnumHeader.SECOND.name()));
Expand Down